Python 1201.py
class Solution:
def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int:
a, b, c = sorted([a, b, c])
if c % a == 0 or c % b == 0:
c = 10**10 # larger than any result
if b % a == 0:
b, c = c, 10**10
ab = a*b // gcd(a, b)
bc = b*c // gcd(b, c)
ac = a*c // gcd(a, c)
abc = a*b*c // gcd(a, b, c)
def ugly(guess):
one = guess // a + guess // b + guess // c
two = guess // ab + guess // bc + guess // ac
three = guess // abc
return one - two + three
result = n * a
step = result // 2
while step > 1:
if ugly(result) >= n:
result -= step
else:
result += step
step //= 2
while ugly(result) >= n:
result -= 1
while ugly(result) < n:
result += 1
return result
Difficulty
and has an acceptance rate of about 32% (100k+ submissions).
Typical patterns to solve this problem:
- Binary Search
- Combinatorics
- Math
- Number Theory
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The nthUglyNumber method returns the n-th positive integer that is divisible by at least one of the three given factors a, b, or c. The implementation first normalizes the factors, pre-computes the least common multiples needed for inclusion-exclusion, defines a helper that counts how many “ugly” numbers are ≤ a guess, and then performs a fast search that converges on the exact answer.
Normalization of Input
a, b, c = sorted([a, b, c])
if c % a == 0 or c % b == 0:
c = 10**10 # larger than any result
if b % a == 0:
b, c = c, 10**10
The three divisors are sorted so that a ≤ b ≤ c. When a larger divisor is a multiple of a smaller one, it can never be the minimal divisor that contributes a new ugly number. The code replaces such redundant divisors with a sentinel value (10**10) that exceeds any possible answer, effectively removing them from the counting logic while keeping the three-variable interface intact.
Least Common Multiple Computations
ab = a*b // gcd(a, b)
bc = b*c // gcd(b, c)
ac = a*c // gcd(a, c)
abc = a*b*c // gcd(a, b, c)
The pairwise and triple least common multiples are derived using the greatest common divisor. These values are essential for the inclusion-exclusion formula that follows, allowing the algorithm to count numbers divisible by multiple factors without double-counting.
Inclusion-Exclusion Helper
def ugly(guess):
one = guess // a + guess // b + guess // c
two = guess // ab + guess // bc + guess // ac
three = guess // abc
return one - two + three
For any guess, ugly(guess) returns the count of integers ≤ guess that are divisible by at least one of the three factors. The formula adds the individual counts (one), subtracts the counts of numbers counted twice (two), and adds back the numbers counted three times (three). This exact count drives the search for the n-th ugly number.
Search Strategy
The algorithm starts with a generous upper bound based on the smallest factor:
result = n * a
step = result // 2
A halving step size is then used to perform a binary-like descent:
while step > 1:
if ugly(result) >= n:
result -= step
else:
result += step
step //= 2
At each iteration the step size is halved, and the direction is chosen by comparing the current count with n. This quickly narrows the interval containing the target value.
Two final linear adjustments guarantee exactness:
while ugly(result) >= n:
result -= 1
while ugly(result) < n:
result += 1
The first loop backs off if the current result overshoots the n-th ugly number, and the second loop steps forward if it undershoots. After these loops, result is precisely the smallest integer whose count matches n.
Edge Cases Handled
When any divisor is a multiple of another, the redundant divisor is replaced by the sentinel 10**10. This ensures that the inclusion-exclusion calculation never counts numbers that could only be produced by a divisor that is already covered by a smaller one. The sentinel is large enough that guess // sentinel evaluates to zero for any realistic guess, effectively removing the term from the count without altering the algorithmic flow.
The initial bound result = n * a works even when a is the smallest divisor, guaranteeing that the n-th ugly number cannot exceed this product. The halving loop’s condition step > 1 prevents an infinite loop when the step size reaches zero, and the subsequent linear adjustments handle the final off-by-one situation that can arise from the coarse halving phase.
Performance Optimizations
Sorting the divisors once at the start reduces the number of conditional checks needed later. Replacing redundant divisors with a sentinel eliminates unnecessary division operations in the ugly helper, because any division by the sentinel yields zero. Pre-computing the pairwise and triple LCMs avoids repeated GCD calculations inside the counting loop.
The search uses a geometric reduction of the step size (step //= 2), which converges in logarithmic iterations relative to the initial bound. This approach avoids a full binary search on a monotonic predicate while still achieving a comparable number of evaluations. The final linear sweeps are bounded by at most one step of the halving phase, ensuring that they add only a constant amount of work.
All arithmetic stays in integer domain, leveraging Python’s fast integer division and multiplication, and the algorithm avoids any auxiliary data structures, keeping the runtime footprint minimal.
ELI5 - Simplified Explanation
Imagine a giant collection of magical building blocks that grow in groups of three. Some grow in groups of size a, some in groups of size b, and others in size c. The task is to find the specific number that belongs to one of these groups when everything is sorted from smallest to largest.
First, the code organizes the groups so the smallest numbers are easy to spot. It ignores groups that are already contained inside other groups because those would just be extra work.
Next, it calculates helpful shortcuts for finding overlaps. If a number is a multiple of two different sizes, it counts it in a special way so the same space is not counted twice.
To find the right answer, the code plays a guessing game. It starts with a big guess and checks how many numbers are in the groups up to that point. If the count is too high, the guess moves down. If it is too low, the guess moves up. By constantly narrowing the search, it gets closer and closer to the exact number.
Finally, once the guess is very close, it checks the neighboring numbers one by one to make sure it has landed on the perfect spot where the count matches exactly what is needed.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||
| WalkCCC | C++ | Python | Java | |||||
| leetcode.ca | C++ | Python | Java | Go | TS | |||
| MemoryLimitExceeded | C++ | Python | ||||||
| Progiez | C++ | Python | Java | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JS | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||
| MemoryLimitExceeded | Python, C++ | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JavaScript | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 264: Ugly Number II
Solved On The Same Day
- problem 563: Binary Tree Tilt
- problem 938: Range Sum of BST
- problem 965: Univalued Binary Tree
- problem 146: LRU Cache
- problem 371: Sum of Two Integers
- problem 865: Smallest Subtree with all the Deepest Nodes
- problem 2707: Extra Characters in a String
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality