Successful Pairs of Spells and Potions — LeetCode 2300 Python Solution

MediumArrayTwo PointersBinary SearchSorting
Problem
#2300
Reading time
2 min

The problem

You are given two positive integer arrays spells and potions, of length n and m respectively, where spells[i] represents the strength of the ith spell and potions[j] represents the strength of the jth potion. You are also given an integer success.

Example

Input
spells = [5,1,3], potions = [1,2,3,4,5], success = 7
Output
[4,0,3]
Explanation
- 0th spell: 5 * [1,2,3,4,5] = [5,10,15,20,25]. 4 pairs are successful.

Python solution

Python
class Solution:
    def successfulPairs(
        self, spells: List[int], potions: List[int], success: int
    ) -> List[int]:
        potions.sort()
        m = len(potions)
        return [m - bisect_left(potions, success / v) for v in spells]

Complexity

MeasureComplexity
TimeO((m + n) \times \log m)
SpaceO(\log n) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 2300. Successful Pairs of Spells and Potions is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

On a study list

This problem is on LeetCode 75.

Frequently asked questions

How hard is LeetCode 2300. Successful Pairs of Spells and Potions?
LeetCode 2300. Successful Pairs of Spells and Potions is rated Medium on LeetCode.
What is the time complexity of LeetCode 2300. Successful Pairs of Spells and Potions?
The Python solution on this page runs in O((m + n) \times \log m).
What is the space complexity of LeetCode 2300. Successful Pairs of Spells and Potions?
The Python solution on this page uses O(\log n) auxiliary space.
What topics does LeetCode 2300. Successful Pairs of Spells and Potions cover?
LeetCode 2300. Successful Pairs of Spells and Potions is tagged Array, Two Pointers, Binary Search and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview