Successful Pairs of Spells and Potions (LeetCode 2300): Solution and Explanation

Medium
Array
Two Pointers
Binary Search
Sorting

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

  1. Sort potions in ascending order and let m be its length.
  2. For each spell s, set lo = 0 and hi = m (the answer index may be m, meaning no potion works).
  3. While lo < hi, take mid. If s * potions[mid] >= success, the first working potion is at mid or earlier, so hi = mid. Otherwise it is after mid, so lo = mid + 1.
  4. When the loop ends, lo is the first working index. Append m - lo.
  5. 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
  1. potions is already sorted: [1,2,3,4,5], m = 5.
  2. 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.
  3. Spell 1: every check fails, since even 1 * 5 = 5 < 7. lo climbs to 5, count 5 - 5 = 0.
  4. Spell 3: mid = 2 gives 9 >= 7 (hi = 2), mid = 1 gives 6 < 7 (lo = 2). Boundary 2, count 3.
  5. 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 result
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

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.

Space

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.