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.
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- Time: O(mlogm + nlogm) β sorting potions costs π ( π log β‘ π ) ; each of the n binary searches costs π ( log β‘ π )
- Space: O(1)