Ugly Number II solution explained
Ugly Number II asks for the n-th positive integer whose only prime factors are 2, 3 and 5, with 1 counted as the first. Every such number is 2, 3 or 5 times a smaller one, so build the list in order with three pointers: the next value is the smallest of 2, 3 and 5 times the number each pointer marks, and every pointer that produced it moves forward. That takes O(n) time and O(n) memory, and a min-heap version takes O(n log n).
By Evin JohnPublished 7 min read
The problem, restated
Call a positive integer smooth here if dividing out every factor of 2, 3 and 5 leaves exactly 1. So 12 qualifies (2 · 2 · 3), and 14 does not (it has a 7). By convention 1 qualifies and is the first such number. Given n, return the n-th number in increasing order. The problem is usually phrased with the word ugly, which is just a name.
| n | Answer | Note |
|---|---|---|
| 1 | 1 | The sequence starts at 1 by convention |
| 7 | 8 | 7 is skipped because it is prime |
| 11 | 15 | 11, 13 and 14 are skipped |
| 15 | 24 | 21 and 22 are skipped along the way |
| 20 | 36 | The gaps keep widening |
What the interviewer is checking
The brute force is obvious, and the interviewer wants to see you notice why it is slow and then switch from testing numbers to generating them. The three-pointer merge is short but has one classic bug, duplicate values, so the conversation often turns to why the pointer updates use separate if statements rather than an if-else chain. The heap version is a fine first answer and leads naturally to the merge.
Follow-ups
- Other primes. With a list of k primes, keep k pointers, or a heap of k candidates. That variant is often called super ugly numbers.
- Is a single number in the set? Divide out 2, 3 and 5 while possible and check whether 1 remains. Treat 0 and negative numbers as not in the set.
- How big do the values get? By term 1,000 the value is 51,200,000, and term 1,691 is the last one below 2^31, so 32-bit limits matter in fixed-width languages.
- Many queries. Generate the list once up to the largest n asked and answer each query by index.
Brute force: test every integer
Walk through 1, 2, 3 and so on, divide each by 2, 3 and 5 as long as possible, and count the ones that reduce to 1. It is correct and easy to write. The trouble is density: these numbers become rare, so the scan reaches 82,944 just to find the 300th, and well over fifty million to find the 1,000th.
def is_smooth(x):
if x <= 0:
return False
for p in (2, 3, 5):
while x % p == 0:
x //= p
return x == 1
def nth_smooth_slow(n):
found, x = 0, 0
while found < n:
x += 1
if is_smooth(x):
found += 1
return xA heap of candidates
Generate instead of test. Start a min-heap with 1. Pop the smallest value; it is the next term. Push that value times 2, 3 and 5, skipping any already pushed. After n pops, the last value popped is the answer. Each pop and push costs O(log n), so the total is O(n log n), with a set to stop duplicates.
import heapq
def nth_smooth_heap(n):
heap, queued = [1], {1}
for _ in range(n):
value = heapq.heappop(heap)
for p in (2, 3, 5):
nxt = value * p
if nxt not in queued:
queued.add(nxt)
heapq.heappush(heap, nxt)
return valueThe optimal approach: three pointers
The heap holds many values that will not be needed for a while. A tighter view: the sequence, multiplied by 2, is itself a sorted stream, and so are the sequence times 3 and times 5. Every term after 1 appears in at least one of those three streams. So merge them. Keep three indexes into the list built so far, one per factor. The next term is the smallest of the three candidates, and every index whose candidate equals it moves forward by one.
def nth_smooth(n):
seq = [1]
i2 = i3 = i5 = 0
while len(seq) < n:
c2, c3, c5 = seq[i2] * 2, seq[i3] * 3, seq[i5] * 5
nxt = min(c2, c3, c5)
seq.append(nxt)
if nxt == c2: # separate ifs: several streams can tie
i2 += 1
if nxt == c3:
i3 += 1
if nxt == c5:
i5 += 1
return seq[n - 1]function nthUglyNumber(n) {
const seq = [1];
let i2 = 0;
let i3 = 0;
let i5 = 0;
while (seq.length < n) {
const c2 = seq[i2] * 2;
const c3 = seq[i3] * 3;
const c5 = seq[i5] * 5;
const next = Math.min(c2, c3, c5);
seq.push(next);
if (next === c2) i2++;
if (next === c3) i3++;
if (next === c5) i5++;
}
return seq[n - 1];
}| Step | Candidates (x2, x3, x5) | Next term | Pointers that move |
|---|---|---|---|
| 1 | 2, 3, 5 | 2 | x2 |
| 2 | 4, 3, 5 | 3 | x3 |
| 3 | 4, 6, 5 | 4 | x2 |
| 4 | 6, 6, 5 | 5 | x5 |
| 5 | 6, 6, 10 | 6 | x2 and x3 together |
| 6 | 8, 9, 10 | 8 | x2 |
Step 5 is the important one. Both the x2 and the x3 streams offer 6. If only one pointer moved, the other would offer 6 again at the next step and the list would contain it twice, shifting every later answer. Separate if statements, not else-if, fix that.
Complexity
| Approach | Time | Extra memory |
|---|---|---|
| Scan and test every integer | Proportional to the size of the answer, which grows much faster than n | O(1) |
| Min-heap with a seen set | O(n log n) | O(n) |
| Three-pointer merge | O(n) | O(n) |
Edge cases
- n = 1 returns 1 without entering the loop.
- Ties between streams, first at 6, then at 10, 12, 15 and many later values.
- Large n in a language with 32-bit integers, where term 1,692 equals 2^31 and no longer fits in a signed 32-bit int.
Common mistakes
- Using if-else for the pointer moves, which lets duplicates into the list.
- Starting the sequence at 2 or forgetting that 1 is the first term.
- Off-by-one in the return: the n-th term is at index n - 1.
- In the heap version, popping duplicates instead of preventing them, which miscounts terms.
- Testing primality instead of dividing out 2, 3 and 5 in the brute force.
How to explain it out loud
Fictional example
- Candidate
- I could test each integer by dividing out 2, 3 and 5, but these numbers get sparse, so the scan wastes most of its time. Better to generate them in order.
- Candidate
- Every term after 1 is 2, 3 or 5 times an earlier term. So the list times 2, times 3 and times 5 are three sorted streams, and I merge them with three pointers into the list I am building.
- Candidate
- Each step takes the smallest candidate and moves every pointer that produced it, so a value like 6 that comes from two streams appears once. Linear time and memory.
Related problems
Perfect Squares is another number-building problem where each value depends on a small set of earlier ones. Kth Smallest Element in a Sorted Matrix uses the same heap-of-candidates idea on rows of a matrix. Merge k Sorted Lists is the general form of merging sorted streams.
Practicing with Natively
The duplicate-pointer detail is exactly what you want to have said out loud a few times before an interview. During practice on Mac or Windows, Natively can read the problem from a screenshot and suggest the merge approach as a comparison for your own attempt, and the transcript of your mock shows whether you explained ties before writing the code. Learn about the AI interview assistant.
Questions people ask
How do you solve Ugly Number II?
Build the sequence in order starting from 1. Keep three pointers for the factors 2, 3 and 5; the next term is the smallest of 2, 3 and 5 times the term each pointer marks, and every pointer whose product equals it moves forward.
Why use separate if statements for the three pointers?
Some values come from two streams, such as 6 = 2 · 3 = 3 · 2. Moving every matching pointer stops that value from being added twice, which would shift every later term.
What is the time complexity of Ugly Number II?
The three-pointer merge is O(n) time and O(n) memory. A min-heap with a set of seen values is O(n log n).
Is 1 an ugly number?
Yes, by the usual convention 1 is the first term, since it has no prime factors at all.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
