Successful Pairs of Spells and Potions — Sort + Binary Search

Sanjeev SharmaSanjeev Sharma
1 min read

Advertisement

Problem 325 · Successful Pairs of Spells and Potions

Difficulty: Medium · Pattern: Sort + Binary Search per query

For each spell, count potions where spell * potion >= success.

Solutions

# Python
import bisect, math
def successfulPairs(spells, potions, success):
    potions.sort()
    res = []
    n = len(potions)
    for s in spells:
        # Need potion >= ceil(success/s)
        threshold = math.ceil(success/s)
        idx = bisect.bisect_left(potions, threshold)
        res.append(n - idx)
    return res
// Java
public int[] successfulPairs(int[] spells, int[] potions, long success) {
    Arrays.sort(potions);
    int n=potions.length; int[] res=new int[spells.length];
    for (int i=0;i<spells.length;i++) {
        long need=(success+spells[i]-1)/spells[i]; // ceil
        int lo=0,hi=n;
        while(lo<hi){int mid=(lo+hi)/2;if(potions[mid]>=need)hi=mid;else lo=mid+1;}
        res[i]=n-lo;
    }
    return res;
}

Complexity

  • Time: O((n+m) log m) where n=spells, m=potions
  • Space: O(1) excluding output

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro