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: Count Valid Combinations513Spells12345PotionsSuccess threshold = 7Spell 5: Products [5,10,15,20,25] → 4 pairs ≥ 7Spell 1: Products [1,2,3,4,5] → 0 pairs ≥ 7Spell 3: Products [3,6,9,12,15] → 3 pairs ≥ 7403Output: [4,0,3]
Understanding the Visualization
1
Input
Spells [5,1,3], potions [1,2,3,4,5], success = 7
2
Process
For each spell, count potions where spell × potion ≥ success
3
Output
Array of counts: [4,0,3]
Key Takeaway
🎯 Key Insight: Sort potions once, then use binary search to find the cutoff point for each spell instead of checking every pair
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