Skip to content
Problem 2300 · LeetCode 2300(opens in a new tab)

Successful Pairs of Spells and Potions

MediumArrays

You have two arrays of positive integers: spells, with n entries, and potions, with m entries. Each number is a strength. You also get a number success.

A spell and a potion make a good pair when their strengths multiplied together are at least success. Return an array of length n whose entry i is how many potions make a good pair with spells[i].

Example 1

Input:  spells = [2, 6, 1], potions = [4, 1, 3, 2], success = 8
Output: [1, 3, 0]
Why:    2 needs a potion of 4; 6 needs 2 or more; 1 would need 8
2 more examples and the constraints

Example 2

Input:  spells = [4, 7], potions = [5, 2, 6], success = 20
Output: [2, 2]
Why:    4 × 5 and 4 × 6 reach 20; so do 7 × 5 and 7 × 6

Example 3

Input:  spells = [10], potions = [10], success = 100
Output: [1]
Why:    10 × 10 is exactly 100, and equal counts

Constraints

  • 1 ≤ n, m ≤ 100,000
  • 1 ≤ spells[i], potions[j] ≤ 100,000
  • 1 ≤ success ≤ 10,000,000,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Try every pairO(n·m)
  2. Sort potions + binary searchO((n + m) log m)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 spells and potionsVerdict
Try every pairO(n·m)
Too slow; 10 billion products
Sort potions + binary searchO((n + m) log m)
Best; one sort, n searches

n = number of spells, m = number of potions.

Edge cases to test

  • Product equal to success. 10 × 10 with success 100 counts: the rule is "at least".
  • No potion is strong enough. The search ends past the last index and the count is 0.
  • Products above 32 bits. 100,000 × 100,000 is 10¹⁰, so use 64-bit math for products and for need.
  • Repeated potions. Find the first potion that is at least need, so equal values are all counted.

Common mistakes

  • Multiplying in 32-bit integers, which overflows past about 2.1 billion.
  • Using floating-point division for need, which can be off by one near 10¹⁰.
  • Searching for the last weak potion with an off-by-one, so equal products are missed or counted twice.

How to talk through it

  1. 1Clarify. Does a product equal to success count? How large can the product get? Must the output keep the spells' order?
  2. 2Give the brute force. Try every pair; say it is O(n·m), 10 billion at the limits.
  3. 3Spot the order. A stronger potion never breaks a good pair, so after sorting, the good potions are a suffix.
  4. 4Code the search. Compute need with an integer ceiling, then a lower-bound binary search; the count is m − lo.
  5. 5Test out loud. Run an exact-equality case and one where no potion works before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?