Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created October 8, 2025 18:05
Show Gist options
  • Select an option

  • Save Ifihan/58d556daa442dc3eee1ad184c515e89f to your computer and use it in GitHub Desktop.

Select an option

Save Ifihan/58d556daa442dc3eee1ad184c515e89f to your computer and use it in GitHub Desktop.
Successful Pairs of Spells and Potions

Question

Approach

I sort the potions array once. For each spell, I compute the minimum potion strength needed so that spell * potion >= success, which is needed = ceil(success / spell). Then I binary-search (bisect_left) in the sorted potions to find the first index with value >= needed; the number of successful potions for that spell is m - index.

Implementation

class Solution:
    def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]:
        potions.sort()
        m = len(potions)
        res = []
        for s in spells:
            needed = (success + s - 1) // s
            idx = bisect.bisect_left(potions, needed)
            res.append(m - idx)
        return res

Complexities

  • Time: O(mlogm + nlogm) β€” sorting potions costs 𝑂 ( π‘š log ⁑ π‘š ) ; each of the n binary searches costs 𝑂 ( log ⁑ π‘š )
  • Space: O(1)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment