Ugly Number III — LeetCode 1201 Python Solution

MediumMathBinary SearchCombinatoricsNumber Theory
Problem
#1201
Reading time
4 min

The problem

An ugly number is a positive integer that is divisible by a, b, or c. Given four integers n, a, b, and c, return the nth ugly number.

Example

Input
n = 3, a = 2, b = 3, c = 5
Output
4
Explanation
The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rd is 4.

Python solution

Python
class Solution:
    def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int:
        ab = lcm(a, b)
        bc = lcm(b, c)
        ac = lcm(a, c)
        abc = lcm(a, b, c)
        l, r = 1, 2 * 10**9
        while l < r:
            mid = (l + r) >> 1
            if (
                mid // a
                + mid // b
                + mid // c
                - mid // ab
                - mid // bc
                - mid // ac
                + mid // abc
                >= n
            ):
                r = mid
            else:
                l = mid + 1
        return l

Complexity

MeasureComplexity
TimeO(\log m), where m = 2 \times 10^9
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 1201. Ugly Number III 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 1201. Ugly Number III?
LeetCode 1201. Ugly Number III is rated Medium on LeetCode.
What is the time complexity of LeetCode 1201. Ugly Number III?
The Python solution on this page runs in O(\log m), where m = 2 \times 10^9.
What is the space complexity of LeetCode 1201. Ugly Number III?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1201. Ugly Number III cover?
LeetCode 1201. Ugly Number III is tagged Math, Binary Search, Combinatorics and Number Theory 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