Problem Description
Given two positive integer arrays spells and potions along with an integer success, determine for each spell the number of potions that form a successful pair. A pair is considered successful if the product of a spell's strength and a potion's strength is at least success.
Key Insights
- Sort the potions array to leverage binary search.
- For each spell, determine the minimum required potion strength using ceiling division.
- Use binary search to efficiently find the first potion that meets or exceeds the required strength.
- The number of valid pairs for a spell is the number of potions to the right of (and including) that position.
Space and Time Complexity
Time Complexity: O(m log m + n log m) where m is the number of potions and n is the number of spells. Space Complexity: O(m) for the sorted potions and O(n) for the result array.
Solution
The solution sorts the potions to allow for binary searching the smallest potion that, when multiplied by a given spell, reaches the success threshold. For each spell, compute the minimum required potion strength using integer math to perform ceiling division: required = (success + spell - 1) // spell. Then, perform a binary search in the sorted potions array to find the first index of a potion that is at least the required strength. The remaining number of potions from that index to the array's end gives the count of successful pairs for that spell.