Successful Pairs of Spells and Potions
Problem
Given two integer arrays spells and potions, and an integer success, return an array where each element is the number of potions that when multiplied with the corresponding spell produce a product greater than or equal to success.
- 1 ≤ spells.length, potions.length ≤ 10⁵
- 1 ≤ spells[i], potions[i] ≤ 10⁵
- 1 ≤ success ≤ 10¹⁰
Example
spells = [5,1,3], potions = [1,2,3,4,5], success = 7[4,0,3]For spell 5, potions that satisfy 5 * potion >= 7 are [2,3,4,5], count = 4. For spell 1, no potion satisfies 1 * potion >= 7, count = 0. For spell 3, potions [3,4,5] satisfy 3 * potion >= 7, count = 3. The algorithm sorts potions to enable binary search. For each spell, it performs a binary search to find the first potion that meets the success threshold, then counts how many potions remain.
Approach
Straightforward Solution
A naive approach would check every pair of spell and potion, resulting in O(n*m) time complexity, which is infeasible for large inputs.
Core Observation
The problem reduces to, for each spell, finding the count of potions where spell * potion >= success. Since potions are positive, this inequality can be rearranged to potion >= ceil(success / spell). This transforms the problem into a search for the lower bound in a sorted array.
Path to Optimal
Sorting potions allows binary search to find the first potion meeting the threshold for each spell in O(log m) time. This reduces the overall complexity to O(n log m). The key insight is transforming the multiplication inequality into a threshold comparison and leveraging sorted order for efficient searching.
Optimal Approach
Sort potions ascending. For each spell, use binary search to find the smallest index in potions where potion >= ceil(success / spell). The count of successful potions is total potions minus this index. Append this count to the result array. Return the result after processing all spells.
Time
O(n log m)
Sorting potions takes O(m log m). For each of the n spells, a binary search on potions takes O(log m), resulting in O(n log m) total after sorting.
Space
O(m)
Sorting potions is done in-place or with O(m) auxiliary space depending on the sorting algorithm. The result array uses O(n) space, which is required for output.
Pattern Spotlight
Binary Search (Lower Bound Search in Sorted Array)
When searching for the count of elements meeting a threshold in a sorted array, use binary search to find the first valid element's index, then subtract from the total length to get the count efficiently.
Solution
| 1 | class Solution: |
| 2 | def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]: |
| 3 | potions.sort() |
| 4 | result = [] |
| 5 | |
| 6 | for spell in spells: |
| 7 | left = 0 |
| 8 | right = len(potions) - 1 |
| 9 | first_successful = len(potions) |
| 10 | |
| 11 | while left <= right: |
| 12 | mid = (left + right) // 2 |
| 13 | |
| 14 | if spell * potions[mid] >= success: |
| 15 | first_successful = mid |
| 16 | right = mid - 1 |
| 17 | else: |
| 18 | left = mid + 1 |
| 19 | |
| 20 | result.append(len(potions) - first_successful) |
| 21 | |
| 22 | return result |
Step-by-Step Solution
Sort Potions to Enable Efficient Threshold Searches
| 3 | potions.sort() |
Objective
To prepare the potions array for binary search by sorting it in ascending order.
Key Insight
Sorting potions is essential because binary search requires a sorted array to function correctly. This preprocessing step transforms the problem from an O(n*m) brute-force search into a more efficient O(n log m) approach by enabling quick threshold lookups.
Interview Quick-Check
Core Logic
Sorting potions allows binary search to find the first potion meeting the success threshold efficiently.
Complexity
Sorting takes O(m log m) time, which is acceptable given the large input size and the efficiency gains in subsequent searches.
Iterate Over Spells and Use Binary Search to Find Threshold Index
| 6 | for spell in spells: |
| 7 | left = 0 |
| 8 | right = len(potions) - 1 |
| 9 | first_successful = len(potions) |
| 11 | while left <= right: |
| 12 | mid = (left + right) // 2 |
| 14 | if spell * potions[mid] >= success: |
| 15 | first_successful = mid |
| 16 | right = mid - 1 |
| 17 | else: |
| 18 | left = mid + 1 |
Objective
For each spell, perform a binary search on potions to find the smallest index where the product meets or exceeds success.
Key Insight
By calculating the required minimum potion value as ceil(success / spell), the binary search locates the first potion that can form a successful pair. This approach avoids checking every potion and leverages the sorted order to discard large portions of the search space quickly.
Interview Quick-Check
Core Logic
Binary search finds the first potion index where spell * potion >= success, enabling O(log m) search per spell.
State & Boundaries
The search space is between left = 0 and right = len(potions) - 1, and the loop continues while left <= right to ensure all candidates are considered.
Common Pitfalls & Bugs
Incorrectly updating left and right pointers or failing to update first_successful index can lead to infinite loops or incorrect counts.
Calculate and Append the Count of Successful Potions for Each Spell
| 20 | result.append(len(potions) - first_successful) |
Objective
To compute the number of potions that form successful pairs with the current spell and append this count to the result list.
Key Insight
Once the binary search identifies the first successful potion index, the count is simply the total potions minus this index. This direct calculation avoids iterating over potions again and efficiently aggregates results for all spells.
Interview Quick-Check
Core Logic
The count of successful potions is total potions minus the first successful potion index found by binary search.
State & Boundaries
Appending results inside the loop ensures the output array aligns with the order of spells.
Return the Final Result Array After Processing All Spells
| 22 | return result |
Objective
To return the array containing counts of successful potions for each spell after all computations are complete.
Key Insight
Returning the result array concludes the function, providing the caller with the required output. This step is straightforward but essential for correctness.
Interview Quick-Check
Core Logic
Returning the result array provides the final answer as specified by the problem.
Line Analysis
This solution has 1 Critical line interviewers watch for.
if spell * potions[mid] >= success:
Check if the product of spell and potion at mid meets or exceeds success.
This comparison is the critical decision point in the binary search, identifying whether to move left or right to find the earliest potion meeting the success threshold.
potions.sort()
Sort the potions array in ascending order.
Sorting is necessary to enable binary search, which requires a sorted array to efficiently find the threshold potion for each spell.
first_successful = mid
Update first_successful to the current mid index when a valid potion is found.
Recording the current mid as a candidate for the first successful potion ensures the algorithm tracks the earliest valid potion index.
result.append(len(potions) - first_successful)
Append the count of successful potions for the current spell to the result list.
Calculating len(potions) - first_successful gives the number of potions meeting the success threshold, which is the required output per spell.
first_successful = len(potions)
Initialize first_successful to the length of potions as a default index.
This default value represents the case where no potion meets the success threshold, allowing correct count calculation by subtracting this index.
right = mid - 1
Move the right pointer left to continue searching for an earlier valid potion.
Adjusting right to mid - 1 narrows the search to the left half, seeking the earliest potion that satisfies the condition.
else:
Move the left pointer right when the current potion fails the success condition.
Incrementing left to mid + 1 discards invalid potions on the left, focusing the search on higher values that might satisfy the condition.
while left <= right:
Start the binary search loop while left pointer is less than or equal to right pointer.
The loop condition ensures the binary search continues until the search space is exhausted, guaranteeing the correct threshold index is found.
mid = (left + right) // 2
Calculate the middle index of the current search space.
Midpoint calculation divides the search space to enable binary search's logarithmic efficiency.
for spell in spells:
Begin iterating over each spell in the spells array.
Processing each spell individually allows the algorithm to find the count of successful potions per spell, which is the problem's requirement.
return result
Return the final list of counts for all spells.
Returning the result completes the function, providing the caller with the computed successful pairs counts.
left = 0
Initialize the left pointer for binary search to the start of potions.
Setting left to 0 defines the lower bound of the search space for the binary search on potions.
right = len(potions) - 1
Initialize the right pointer for binary search to the end of potions.
Setting right to len(potions) - 1 defines the upper bound of the search space for the binary search.
left = mid + 1
Continue the binary search loop.
This line is part of the loop structure that ensures the binary search iterates until the search space is exhausted.
Test Your Understanding
Why is binary search the appropriate method to find the count of potions that satisfy the success condition for each spell?
Because potions are sorted, binary search efficiently finds the first potion that meets the threshold, enabling O(log m) time per spell instead of scanning all potions, which would be O(m). This leverages the sorted order to quickly locate the boundary between failing and successful potions.
Related Problems
Binary Search pattern
Don't just read it. Drill it.
Reconstruct Successful Pairs of Spells and Potions from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.
Unlock the Successful Pairs of Spells and Potions drill