#2300

Successful Pairs of Spells and Potions

Medium
ArrayTwo PointersBinary SearchSortingBinary SearchSorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n + n log m)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n + n log m)Space O(1)

By sorting the potions and using binary search, we can efficiently find the number of successful potions for each spell. This reduces the time complexity significantly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Sort the potions array.
  2. 2Step 2: For each spell, calculate the minimum required potion strength as success / spell.
  3. 3Step 3: Use binary search to find the first potion that meets or exceeds this minimum required strength.
  4. 4Step 4: The number of successful potions is the total potions minus the index found in the previous step.
solution.py9 lines
1def successfulPairs(spells, potions, success):
2    potions.sort()
3    result = []
4    from bisect import bisect_left
5    for spell in spells:
6        min_potion = success / spell
7        index = bisect_left(potions, min_potion)
8        result.append(len(potions) - index)
9    return result

Complexity note: The sorting of potions takes O(m log m), and for each spell, we perform a binary search in O(log m), leading to a total of O(n log m).

  • 1If a spell can pair successfully with a potion, it can also pair successfully with all stronger potions.
  • 2Sorting allows us to efficiently find the first successful potion using binary search.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.