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

Examples written for this page
nAnswerNote
11The sequence starts at 1 by convention
787 is skipped because it is prime
111511, 13 and 14 are skipped
152421 and 22 are skipped along the way
2036The gaps keep widening
Examples written for this page. Scroll sideways on a small screen.

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 x
Python: scan and test. Correct, but far too slow for large n.

A 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 value
Python: min-heap plus a set of values already queued.

The 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]
Python: merge three streams. O(n) time, O(n) memory.
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];
}
JavaScript: the same merge.
The first steps of the merge (candidates are 2, 3 and 5 times the marked terms)
StepCandidates (x2, x3, x5)Next termPointers that move
12, 3, 52x2
24, 3, 53x3
34, 6, 54x2
46, 6, 55x5
56, 6, 106x2 and x3 together
68, 9, 108x2
The first steps of the merge (candidates are 2, 3 and 5 times the marked terms). Scroll sideways on a small screen.

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

Finding the n-th term
ApproachTimeExtra memory
Scan and test every integerProportional to the size of the answer, which grows much faster than nO(1)
Min-heap with a seen setO(n log n)O(n)
Three-pointer mergeO(n)O(n)
Finding the n-th term. Scroll sideways on a small screen.

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

From testing to generating
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.

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.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP