Successful Pairs of Spells and Potions - Problem

You are given two positive integer arrays spells and potions, of length n and m respectively, where spells[i] represents the strength of the ith spell and potions[j] represents the strength of the jth potion.

You are also given an integer success. A spell and potion pair is considered successful if the product of their strengths is at least success.

Return an integer array pairs of length n where pairs[i] is the number of potions that will form a successful pair with the ith spell.

Input & Output

Example 1 — Basic Case
$ Input: spells = [5,1,3], potions = [1,2,3,4,5], success = 7
Output: [4,0,3]
💡 Note: Spell 5: 5×1=5, 5×2=10≥7, 5×3=15≥7, 5×4=20≥7, 5×5=25≥7 → 4 pairs. Spell 1: all products < 7 → 0 pairs. Spell 3: 3×3=9≥7, 3×4=12≥7, 3×5=15≥7 → 3 pairs.
Example 2 — Higher Success Threshold
$ Input: spells = [3,1,2], potions = [8,5,8], success = 16
Output: [2,0,2]
💡 Note: Spell 3: 3×8=24≥16 (appears twice) → 2 pairs. Spell 1: all products < 16 → 0 pairs. Spell 2: 2×8=16≥16 (appears twice) → 2 pairs.
Example 3 — Edge Case Small Arrays
$ Input: spells = [1], potions = [1], success = 1
Output: [1]
💡 Note: Single spell 1 and single potion 1: 1×1=1≥1, so 1 successful pair.

Constraints

  • 1 ≤ spells.length, potions.length ≤ 105
  • 1 ≤ spells[i], potions[i] ≤ 105
  • 1 ≤ success ≤ 1010

Visualization

Tap to expand
Successful Pairs of Spells and Potions INPUT spells[] array: 5 1 3 idx: 0 1 2 potions[] array: 1 2 3 4 5 success threshold: 7 Condition: spell * potion >= 7 n=3, m=5, success=7 ALGORITHM STEPS 1 Sort Potions [1,2,3,4,5] (already sorted) 2 For each spell Calculate min_potion needed min = ceil(7/spell) 3 Binary Search Find first potion >= min 4 Count Pairs pairs[i] = m - index Calculations: spell=5: min=ceil(7/5)=2 idx=1, count=5-1=4 spell=1: min=ceil(7/1)=7 idx=5, count=5-5=0 spell=3: min=ceil(7/3)=3 idx=2, count=5-2=3 FINAL RESULT Output pairs[] array: 4 0 3 idx: 0 1 2 Spell 5: 4 potions work (2,3,4,5) 5*2=10, 5*3=15, 5*4=20, 5*5=25 All >= 7 [OK] Spell 1: 0 potions (max 1*5=5 < 7) Spell 3: 3 potions work (3,4,5) 3*3=9, 3*4=12, 3*5=15 [OK] Output: [4,0,3] Key Insight: Sort potions once, then use binary search for each spell to find the minimum effective potion. Time: O((m+n) log m) - sorting O(m log m) + n binary searches O(n log m). Space: O(1) extra (excluding output). Much faster than brute force O(n*m)! TutorialsPoint - Successful Pairs of Spells and Potions | Optimal Solution (Binary Search)
Asked in
Meta 25 Amazon 20 Google 15
28.0K Views
Medium Frequency
~25 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen