InterviewPrepKit

Home / Coding / Binary Search

Successful Pairs of Spells and Potions

medium Original β†—
Solving tips
  • For a fixed spell s, potion p succeeds iff p >= success/s; sort potions once so the successes form a suffix and each spell's count is m minus the boundary index.
  • Per spell, binary search (bisect_left) for the first potion >= the cutoff; compute the cutoff with integer ceiling division need = (success + s - 1)//s to avoid float rounding at values up to 1e10.
  • Target O((n+m) log m) time; use bisect_left (not bisect_right) so pairs meeting the threshold exactly still count.
  • Alternative: sort both and sweep spells strongest-to-weakest with a monotonic two-pointer, collapsing the n searches into one pass (carry original indices for output order).

Problem

You have an array spells of spell strengths and an array potions of potion strengths. A spell–potion pair is successful when the product of their strengths is at least a given threshold success.

For each spell, count how many potions form a successful pair with it. Return the counts as an array pairs where pairs[i] corresponds to spells[i].

Examples

  • spells = [5,1,3], potions = [1,2,3,4,5], success = 7 β†’ [4,0,3] Spell 5 pairs with potions 2,3,4,5 (products 10,15,20,25); spell 1 reaches at most 5; spell 3 pairs with 3,4,5 (products 9,12,15).
  • spells = [3,1,2], potions = [8,5,8], success = 16 β†’ [2,0,2] Spell 3: products 24,15,24 β†’ two successes; spell 1 maxes at 8; spell 2: 16,10,16 β†’ two successes.
  • spells = [10], potions = [1,1,1], success = 100 β†’ [0] Every product is 10, below the threshold.

Constraints

  • 1 <= len(spells), len(potions) <= 10^5
  • 1 <= spells[i], potions[j] <= 10^5
  • 1 <= success <= 10^10
  • The sizes rule out checking all n * m pairs (up to 10^10 products).

Think about it first

Hint 1 For a fixed spell of strength `s`, which potions succeed? Is there a single cutoff value that separates failures from successes?
Hint 2 A potion `p` succeeds with spell `s` exactly when `p >= success / s`. If the potions are sorted, all successful potions form a suffix of the array.
Hint 3 Sort `potions` once. For each spell, binary search for the first potion `>= ceil(success / s)` β€” or use `bisect_left` with the exact fraction β€” and the answer is `m` minus that index. Watch out for floating-point: prefer integer ceiling division `(success + s - 1) // s`.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.