In this problem, you are given two arrays of positive integers: spells and potions. You are also given an integer success. A pair of a spell and a potion is considered "successful" if the product of their strengths is at least success. For each spell, your task is to determine how many potions in the potions array can form a successful pair with it.
This is a popular medium-level question at companies like Goldman Sachs and Meta because it tests the transition from a brute-force approach to an optimized one. A naive solution would involve checking every potion for every spell (O(N*M)), which is too slow. The problem requires sorting and searching techniques, which are fundamental to efficient data processing. It also checks if the candidate can handle potential integer overflows when multiplying large numbers.
The most effective pattern for this problem is Sorting combined with Binary Search. First, you sort the potions array. Then, for each spell, you calculate the minimum potion strength needed: min_potion = ceil(success / spell). You then use binary search (specifically a "lower bound" search) on the sorted potions array to find the first potion that is at least min_potion. All potions from that index to the end of the array are successful pairs.
Suppose spells = [5, 1, 3], potions = [1, 2, 3, 4, 5], and success = 7.
7 / 5 = 1.4. The potions [2, 3, 4, 5] work. Count = 4.7 / 1 = 7. None of the potions are ≥ 7. Count = 0.7 / 3 = 2.33. Potions [3, 4, 5] work. Count = 3.
The final result is [4, 0, 3].success / spell can lead to precision issues. It's safer to use (success + spell - 1) // spell for ceiling division or use the condition spell * potion >= success.spells array instead of potions. While sorting spells could help with a two-pointer approach, binary search on potions is usually more direct.Whenever you need to count how many elements in an array satisfy a "greater than" or "less than" condition relative to a target, think of Sorting + Binary Search. It's a classic optimization that reduces O(N) searching to O(log N), significantly improving performance.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Friends Of Appropriate Ages | Medium | Solve | |
| Number of Subsequences That Satisfy the Given Sum Condition | Medium | Solve | |
| Count the Number of Fair Pairs | Medium | Solve | |
| Heaters | Medium | Solve | |
| The Latest Time to Catch a Bus | Medium | Solve |