Magicsheet logo

Successful Pairs of Spells and Potions

Medium
45.6%
Updated 6/1/2025

Successful Pairs of Spells and Potions

What is this problem about?

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.

Why is this asked in interviews?

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.

Algorithmic pattern used

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.

Example explanation

Suppose spells = [5, 1, 3], potions = [1, 2, 3, 4, 5], and success = 7.

  • For spell 5: We need a potion of strength at least 7 / 5 = 1.4. The potions [2, 3, 4, 5] work. Count = 4.
  • For spell 1: We need a potion of strength at least 7 / 1 = 7. None of the potions are ≥ 7. Count = 0.
  • For spell 3: We need a potion of strength at least 7 / 3 = 2.33. Potions [3, 4, 5] work. Count = 3. The final result is [4, 0, 3].

Common mistakes candidates make

  1. Floating point errors: Using standard division like 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.
  2. Linear Search: Using a loop to count potions for each spell, resulting in O(N*M) complexity and TLE.
  3. Sorting the wrong array: Sorting the spells array instead of potions. While sorting spells could help with a two-pointer approach, binary search on potions is usually more direct.

Interview preparation tip

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.

Similar Questions