LeetCode #264 Medium

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.
  • n is at most 1690. The 1690th ugly number is 2,123,366,400, which still fits in a 32-bit int.

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.

Constraints
  • 1 <= n <= 1690
dynamic-programmingheapmath
Open on LeetCode ↗
02

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.

How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def nthUglyNumber(self, n: int) -> int:
▶3 ugly = [1] * n
▶4 i2 = i3 = i5 = 0
▶5 for k in range(1, n):
▶6 a, b, c = ugly[i2] * 2, ugly[i3] * 3, ugly[i5] * 5
▶7 ugly[k] = min(a, b, c)
▶8 if ugly[k] == a:
▶9 i2 += 1
▶10 if ugly[k] == b:
▶11 i3 += 1
▶12 if ugly[k] == c:
▶13 i5 += 1
▶14 return ugly[n - 1]
ugly numbers in order1×2×3×5next candidates×2=×3=×5=start: 1 is the first ugly number
written1
1 has no prime factors, so it is ugly and comes first. All three pointers start on it: each prime still has to multiply the term 1, giving the first candidates 2, 3 and 5.
ugly numbers in order12×2×3×5next candidates1×2=2picked → pointer moves1×3=3not picked, stays1×5=5not picked, stayssmallest is 2 → write it
position2
candidates2, 3, 5
picked2
The three streams are each sorted, so the smallest front value, 2, is the smallest ugly number not yet written. Only the ×2 pointer made it, so only that one moves to the next term.
ugly numbers in order123×2×3×5next candidates2×2=4not picked, stays1×3=3picked → pointer moves1×5=5not picked, stayssmallest is 3 → write it
position3
candidates4, 3, 5
picked3
The three streams are each sorted, so the smallest front value, 3, is the smallest ugly number not yet written. Only the ×3 pointer made it, so only that one moves to the next term.
ugly numbers in order1234×2×3×5next candidates2×2=4picked → pointer moves2×3=6not picked, stays1×5=5not picked, stayssmallest is 4 → write it
position4
candidates4, 6, 5
picked4
The three streams are each sorted, so the smallest front value, 4, is the smallest ugly number not yet written. Only the ×2 pointer made it, so only that one moves to the next term.
ugly numbers in order12345×2×3×5next candidates3×2=6not picked, stays2×3=6not picked, stays1×5=5picked → pointer movessmallest is 5 → write it
position5
candidates6, 6, 5
picked5
The three streams are each sorted, so the smallest front value, 5, is the smallest ugly number not yet written. Only the ×5 pointer made it, so only that one moves to the next term.
ugly numbers in order123456×2×3×5next candidates3×2=6picked → pointer moves2×3=6picked → pointer moves2×5=10not picked, stays6 made two ways → write it once, move both
position6
candidates6, 6, 10
picked6
3 × 2 and 2 × 3 both give 6. It is written once, and every pointer that produced it moves on, so no stream can offer 6 again.
ugly numbers in order1234568×2×3×5next candidates4×2=8picked → pointer moves3×3=9not picked, stays2×5=10not picked, stayssmallest is 8 → write it
position7
candidates8, 9, 10
picked8
The three streams are each sorted, so the smallest front value, 8, is the smallest ugly number not yet written. Only the ×2 pointer made it, so only that one moves to the next term.
ugly numbers in order12345689×2×3×5next candidates5×2=10not picked, stays3×3=9picked → pointer moves2×5=10not picked, stayssmallest is 9 → write it
position8
candidates10, 9, 10
picked9
The three streams are each sorted, so the smallest front value, 9, is the smallest ugly number not yet written. Only the ×3 pointer made it, so only that one moves to the next term.
ugly numbers in order1234568910×2×3×5next candidates5×2=10picked → pointer moves4×3=12not picked, stays2×5=10picked → pointer moves10 made two ways → write it once, move both
position9
candidates10, 12, 10
picked10
5 × 2 and 2 × 5 both give 10. It is written once, and every pointer that produced it moves on, so no stream can offer 10 again.
ugly numbers in order123456891012×2×3×5next candidates6×2=12picked → pointer moves4×3=12picked → pointer moves3×5=15not picked, stays12 made two ways → write it once, move both
position10
candidates12, 12, 15
picked12
6 × 2 and 4 × 3 both give 12. It is written once, and every pointer that produced it moves on, so no stream can offer 12 again.
ugly numbers in order123456891012×2×3×5next candidates×2=×3=×5=ugly number 10 is 12
answer12
Each step wrote one new value, always larger than the one before, so the last slot holds ugly number 10, which is 12.
05

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.

▶1class Solution:
▶2 def nthUglyNumber(self, n: int) -> int:
▶3 heap = [1]
▶4 seen = {1}
▶5 for _ in range(n):
▶6 x = heapq.heappop(heap)
▶7 for p in (2, 3, 5):
▶8 if x * p not in seen:
▶9 seen.add(x * p)
▶10 heapq.heappush(heap, x * p)
▶11 return x
06

Common pitfalls

Using elif, so only one pointer moves on a tie

✗ Wrong
if ugly[k] == a:
    i2 += 1
elif ugly[k] == b:
    i3 += 1
elif ugly[k] == c:
    i5 += 1
✓ Right
if ugly[k] == a:
    i2 += 1
if ugly[k] == b:
    i3 += 1
if ugly[k] == c:
    i5 += 1

At 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.

07

Edge cases

n = 1

The loop does not run and ugly[0] = 1 is returned, because 1 is the first ugly number.

08

Complexity

Time
O(n)
Space
O(n)
Each of the n − 1 positions needs three multiplications, one minimum and three comparisons. The array of n terms is the only storage, and the pointers need it because they read terms written long ago.
09

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.