Ugly Number II
Ugly Number II is LeetCode 264 (Medium). Given n, return the nth ugly number.
- Ugly numbers are the positive integers with no prime factor other than 2, 3 and 5.
- The sequence starts 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, so the 10th one is 12.
nis at most 1690. The 1690th ugly number is 2,123,366,400, which still fits in a 32-bitint.
Checking 1, 2, 3, … one at a time would work in principle, but ugly numbers thin out fast: the 1690th is over two billion, so a scan would test billions of numbers.
- 1 <= n <= 1690
Intuition
Every ugly number except 1 is a smaller ugly number times 2, 3 or 5. So the whole sequence is 1 followed by three sorted streams merged together:
- Times 2: 1·2, 2·2, 3·2, 4·2, … (each term of the sequence doubled)
- Times 3: 1·3, 2·3, 3·3, …
- Times 5: 1·5, 2·5, 3·5, …
Keep one pointer per stream, aimed at the term it will multiply next. The next ugly number is the smallest of the three candidates. Every pointer whose candidate equals that minimum moves forward, which is how a value like 6, made both as 3·2 and 2·3, is written only once.
When a sorted sequence is made by multiplying its own earlier terms by a few fixed factors, merge those few "times p" streams like sorted lists, one pointer per stream. Super Ugly Number is the same idea with k primes and a heap.
Approach
Before reading on, write 1, 2, 3, 4, 5, 6 and ask where each one came from: which earlier term times 2, 3 or 5? Then guess the next term, and notice that 6 can be reached in two ways.
Two ways to solve it
Merge the ×2, ×3 and ×5 streams with one index each.
- Linear: one comparison of three numbers per term.
- Repeats: handled by moving every pointer that ties.
Pop the smallest number, push it times 2, 3 and 5, and skip anything already pushed.
- Easy to trust: it is a plain "smallest first" search.
- Generalises: works for any list of primes.
Both produce ugly numbers in increasing order. The pointer merge is faster and uses only the answer array, so the steps, code and live demo follow it. The heap version comes after the demo.
Start the sequence with 1
Make an array ugly of length n with ugly[0] = 1, and set three pointers i2 = i3 = i5 = 0. Each pointer marks the term its prime has not yet multiplied, so at the start all three point at 1.
Pick the smallest candidate
For each position k from 1 to n - 1, compute ugly[i2] * 2, ugly[i3] * 3 and ugly[i5] * 5, and store the smallest in ugly[k]. The three streams are each sorted, so the smallest front value is the smallest number not yet written.
Advance every pointer that produced it
Use three separate if checks, not if/elif. When two candidates tie, as 3·2 and 2·3 do at 6, both pointers must move, or the stream left behind offers 6 again and it lands in the array twice.
Return the last term
After the loop, ugly[n - 1] is the answer. Each step adds exactly one new value in increasing order, so position n - 1 holds the nth ugly number.
Code in Python, C++ and Java
Min-heap with a seen set
Start a min-heap with 1. Pop the smallest value n times; each pop is the next ugly number, and its three multiples go into the heap unless they were pushed before. The seen set is what stops 6 from being pushed by both 2 and 3. Values in the heap can pass the 32-bit limit near n = 1690, so C++ and Java store them as 64-bit.
Common pitfalls
Using elif, so only one pointer moves on a tie
if ugly[k] == a:
i2 += 1
elif ugly[k] == b:
i3 += 1
elif ugly[k] == c:
i5 += 1if ugly[k] == a:
i2 += 1
if ugly[k] == b:
i3 += 1
if ugly[k] == c:
i5 += 1At position 5, both 3·2 and 2·3 equal 6. With elif, only i2 moves, so the ×3 stream still offers 6 and the sequence becomes 1, 2, 3, 4, 5, 6, 6, 8 … For n = 7 the answer comes out 6 instead of 8.
Edge cases
n = 1The loop does not run and ugly[0] = 1 is returned, because 1 is the first ugly number.
Complexity
Ugly Number II FAQ
Why can every pointer read from the array the loop is still writing?
A pointer never passes the write position. The term it reads, times at least 2, is a candidate larger than the last value written, so the pointer always points at a term that already exists.
Can I just precompute all 1690 ugly numbers?
Yes. Many accepted answers build the table once, in a static field, and answer each call with a lookup. The building step is the same three-pointer loop with n = 1690.
How do I check whether one number is ugly?
That is the simpler question in Ugly Number: divide out 2, 3 and 5 as many times as they go, and the number is ugly exactly when 1 is left.