Successful Pairs of Spells and Potions (LeetCode 2300): Solution and Explanation
For every spell, count how many potions give a product of at least success when multiplied by the spell's strength.
Intuition
Fix one spell of strength s. A potion p works when s * p >= success, which is the same as p >= ceil(success / s). So each spell has a single cutoff strength, and every potion at or above it works.
If the potions are sorted, the potions at or above any cutoff sit together at the right end of the array. Counting them only needs the index where that block starts.
Finding the first index whose value passes a monotone test is exactly what binary search does. Sort once for O(m log m), then spend O(log m) per spell.
Approach: Sort + binary search per spell
- Sort
potionsin ascending order and letmbe its length. - For each spell
s, setlo = 0andhi = m(the answer index may bem, meaning no potion works). - While
lo < hi, takemid. Ifs * potions[mid] >= success, the first working potion is atmidor earlier, sohi = mid. Otherwise it is aftermid, solo = mid + 1. - When the loop ends,
lois the first working index. Appendm - lo. - Return the list of counts in the original spell order.
Step-by-step example
spells = [5,1,3], potions = [1,2,3,4,5], success = 7
- potions is already sorted: [1,2,3,4,5], m = 5.
- Spell 5: mid = 2 gives 15 >= 7 (hi = 2), mid = 1 gives 10 >= 7 (hi = 1), mid = 0 gives 5 < 7 (lo = 1). Boundary 1, count 5 - 1 = 4.
- Spell 1: every check fails, since even 1 * 5 = 5 < 7. lo climbs to 5, count 5 - 5 = 0.
- Spell 3: mid = 2 gives 9 >= 7 (hi = 2), mid = 1 gives 6 < 7 (lo = 2). Boundary 2, count 3.
- The answer is [4,0,3].
Code: Python, Java, C++
1class Solution:
2 def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]:
3 potions.sort()
4 m = len(potions)
5 result = []
6 for s in spells:
7 lo, hi = 0, m
8 while lo < hi:
9 mid = (lo + hi) // 2
10 if s * potions[mid] >= success:
11 hi = mid
12 else:
13 lo = mid + 1
14 result.append(m - lo)
15 return result1class Solution {
2 public int[] successfulPairs(int[] spells, int[] potions, long success) {
3 Arrays.sort(potions);
4 int m = potions.length;
5 int[] result = new int[spells.length];
6 for (int i = 0; i < spells.length; i++) {
7 int lo = 0, hi = m;
8 while (lo < hi) {
9 int mid = (lo + hi) / 2;
10 if ((long) spells[i] * potions[mid] >= success) {
11 hi = mid;
12 } else {
13 lo = mid + 1;
14 }
15 }
16 result[i] = m - lo;
17 }
18 return result;
19 }
20}1class Solution {
2public:
3 vector<int> successfulPairs(vector<int>& spells, vector<int>& potions, long long success) {
4 sort(potions.begin(), potions.end());
5 int m = potions.size();
6 vector<int> result;
7 for (int s : spells) {
8 int lo = 0, hi = m;
9 while (lo < hi) {
10 int mid = (lo + hi) / 2;
11 if ((long long) s * potions[mid] >= success) {
12 hi = mid;
13 } else {
14 lo = mid + 1;
15 }
16 }
17 result.push_back(m - lo);
18 }
19 return result;
20 }
21};Time and space complexity
O((n + m) log m)
Sorting the potions takes O(m log m). Each of the n spells then runs one binary search of O(log m) steps.
O(log m)
The sort uses O(log m) stack space in most libraries. The output array of n counts is not counted as extra space.
Other approaches
Brute force (time O(n m), space O(1))
Multiply every spell by every potion and count the products that reach success. Simple, but 10^10 operations at the largest size.
Sort both + two pointers (time O(n log n + m log m), space O(n))
Sort spells (remembering original indices) and potions. As the spell grows, the cutoff index only moves left, so one pointer sweeps the potions once from the right.
Common mistakes
- Integer overflow: spells[i] * potions[j] can be 10^10, which does not fit in a 32-bit int. Cast to long before multiplying in Java, C++, C# and Go.
- Starting hi at m - 1 instead of m. When no potion works the boundary is m, and a closed range cannot return it without a special case.
- Sorting the spells without tracking their indices. The answer must follow the original spell order.
- Computing the cutoff with floating point division. Compare the product directly, or use integer ceiling (success + s - 1) / s.
Frequently asked questions
Why sort the potions and not the spells?
The count for each spell is the size of a suffix of the potions, so the potions are what we search. The spells keep their original order, so the answer lines up with the input.
Why does the binary search use the half-open range [lo, hi)?
The answer index can be m, one past the last potion, when no potion is strong enough. With hi starting at m, the loop naturally lands on m in that case and m - lo gives 0.
Is the two pointer version faster?
It saves the log factor on the per-spell work but adds a sort of the spells. Both are O((n + m) log(n + m)) overall, and the binary search version is shorter to write correctly.