Leetcode 2300: Successful Pairs of Spells and Potions

grid47
grid47
Exploring patterns and algorithms
Mar 22, 2024 6 min read

You are given two arrays: spells and potions, representing the strength of spells and potions, respectively. Each element in the arrays represents the strength of a specific spell or potion. You are also given an integer success, which defines the minimum product of a spell and a potion required for a successful pair. For each spell, determine how many potions can pair with it to form a successful combination (i.e., their product is greater than or equal to success).
Problem
Approach
Steps
Complexity
Input: The input consists of two integer arrays `spells` and `potions`, followed by an integer `success`.
Example: Input: spells = [4, 1, 6], potions = [1, 2, 3, 4, 5], success = 10
Constraints:
• 1 <= n, m <= 10^5
• 1 <= spells[i], potions[i] <= 10^5
• 1 <= success <= 10^10
Output: Return an integer array where each element at index `i` represents the number of potions that will form a successful pair with the `i`-th spell.
Example: Output: [4, 0, 4]
Constraints:
Goal: For each spell, determine how many potions can create a product greater than or equal to the `success` value.
Steps:
• Step 1: Sort the `potions` array in non-decreasing order.
• Step 2: For each spell, calculate the target potion strength that would form a successful pair (i.e., the minimum potion strength needed).
• Step 3: Use binary search to find the number of potions that meet the condition for success.
• Step 4: Return the results for all spells.
Goal: The solution must handle large inputs efficiently and return correct results within the time limits.
Steps:
• Ensure that the solution works within the given bounds for `n`, `m`, and `success`.
Assumptions:
• The input arrays are non-empty and contain valid values within the given ranges.
• The arrays `spells` and `potions` may have different lengths, but both are within the bounds of 1 and 100,000 elements.
Input: Input: spells = [4, 1, 6], potions = [1, 2, 3, 4, 5], success = 10
Explanation: The 0th spell (4) forms successful pairs with potions [3, 4, 5] (products: 12, 16, 20). The 1st spell (1) forms no successful pairs. The 2nd spell (6) forms successful pairs with potions [2, 3, 4, 5] (products: 12, 18, 24, 30). Hence, the output is [4, 0, 4].

Input: Input: spells = [3, 1, 2], potions = [8, 5, 8], success = 16
Explanation: The 0th spell (3) forms successful pairs with potions [8, 8] (products: 24, 24). The 1st spell (1) forms no successful pairs. The 2nd spell (2) forms successful pairs with potions [8, 8] (products: 16, 16). Hence, the output is [2, 0, 2].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus