Ugly Number II (LeetCode 264): Solution and Explanation

Medium
Hash Table
Math
Dynamic Programming
Heap

Ugly numbers are positive integers whose only prime factors are 2, 3 and 5, with 1 counted as the first one. Given n, return the nth ugly number in increasing order.

Intuition

Checking integers one by one and dividing out 2, 3 and 5 works, but the ugly numbers thin out quickly. The 1690th one is over two billion, so a scan would test billions of numbers to collect 1690 hits.

Turn it around and generate only ugly numbers. Every ugly number except 1 is a smaller ugly number multiplied by 2, 3 or 5. So the whole sequence is 1 followed by the merge of three streams: the sequence times 2, the sequence times 3 and the sequence times 5.

Each of those streams is sorted because the sequence itself is sorted. Merging sorted streams only needs one pointer per stream: look at the head of each, take the smallest, and advance. The twist is that the streams are made from the very list you are building, so each pointer is just an index into that list.

Some numbers appear in more than one stream, such as 6 = 2 x 3 = 3 x 2. When the minimum ties across streams, advance every pointer that produced it, so the value is written only once.

Approach: Three pointers over the sequence being built

  1. Create ugly of length n with ugly[0] = 1, and set i2 = i3 = i5 = 0.
  2. For each k from 1 to n - 1, compute the three candidates ugly[i2] * 2, ugly[i3] * 3 and ugly[i5] * 5.
  3. Store the smallest candidate in ugly[k].
  4. Advance each pointer whose candidate equals ugly[k]. More than one pointer can move in the same step.
  5. Return ugly[n - 1].

Step-by-step example

n = 10
  1. Start with ugly = [1] and all three pointers on index 0. The candidates are 2, 3 and 5.
  2. 2 is smallest, so ugly[1] = 2 and i2 moves to index 1. Candidates become 4, 3, 5, so ugly[2] = 3 and i3 moves.
  3. Next come 4 (from 2 x 2) and 5 (from 1 x 5), moving i2 and then i5.
  4. At k = 5 the candidates are 3 x 2 = 6 and 2 x 3 = 6. The value 6 is written once and both i2 and i3 advance.
  5. The pattern continues with 8, 9, 10 (a tie between 5 x 2 and 2 x 5) and 12.
  6. The sequence is 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, so the 10th ugly number is 12.

Code: Python, Java, C++

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            next2, next3, next5 = ugly[i2] * 2, ugly[i3] * 3, ugly[i5] * 5
7            ugly[k] = min(next2, next3, next5)
8            if ugly[k] == next2:
9                i2 += 1
10            if ugly[k] == next3:
11                i3 += 1
12            if ugly[k] == next5:
13                i5 += 1
14        return ugly[n - 1]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each of the n - 1 iterations does a constant amount of work: three multiplications, a minimum and up to three pointer moves.

Space

O(n)

The sequence array holds n numbers, and the pointers need to look back into it.

Other approaches

Min-heap with a seen set (time O(n log n), space O(n))

Push 1 into a min-heap. Pop the smallest value n times, and after each pop push its products with 2, 3 and 5 unless they were already seen. The nth pop is the answer. It is easy to reason about but pays a log factor per operation and stores about 3n values.

Check every integer (time O(answer), space O(1))

Divide each integer by 2, 3 and 5 while possible and count it if 1 remains. This is far too slow for n = 1690, because the answer is above two billion.

Common mistakes

  • Using elif when advancing pointers. On a tie such as 6 only one pointer moves, and the next iteration produces 6 again as a duplicate.
  • Advancing the pointer by the factor instead of by one index. The pointer walks the sequence, one ugly number at a time.
  • Multiplying in 32-bit integers near the end of the range. Candidates for the last few positions sit close to the int limit, so a 64-bit type is the safer choice.
  • Forgetting that 1 is the first ugly number, which shifts every answer by one position.

Frequently asked questions

Why does advancing every matching pointer remove duplicates?

A duplicate only appears when two streams offer the same value at the same time. Moving every pointer that offered it means none of them can offer it again, so each value is written once.

Why is this filed under heaps if the best solution uses no heap?

The heap solution is the natural first idea: always pop the smallest unseen ugly number. The three-pointer version is the same merge with the heap replaced by a three-way minimum, which is faster and simpler.

How is this different from Ugly Number I?

Ugly Number asks whether one given number is ugly, which you answer by dividing out 2, 3 and 5. This problem asks for the nth one, which needs a way to generate them in order.

What is the time complexity of Ugly Number II?

O(n) time and O(n) space with the three-pointer method, versus O(n log n) with a min-heap.