Nth Magical Number — LeetCode 878 Python Solution

HardMathBinary Search
Problem
#878
Reading time
2 min

The problem

A positive integer is magical if it is divisible by either a or b. Given the three integers n, a, and b, return the nth magical number.

Example

Input
n = 1, a = 2, b = 3
Output
2

Python solution

Python
class Solution:
    def nthMagicalNumber(self, n: int, a: int, b: int) -> int:
        mod = 10**9 + 7
        c = lcm(a, b)
        r = (a + b) * n
        return bisect_left(range(r), x=n, key=lambda x: x // a + x // b - x // c) % mod

Complexity

MeasureComplexity
TimeO(log n) or O(n log n)
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 878. Nth Magical Number is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 878. Nth Magical Number?
LeetCode 878. Nth Magical Number is rated Hard on LeetCode.
What topics does LeetCode 878. Nth Magical Number cover?
LeetCode 878. Nth Magical Number is tagged Math and Binary Search 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