Ugly Number II (LeetCode 264): Solution and Explanation
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
- Create
uglyof lengthnwithugly[0] = 1, and seti2 = i3 = i5 = 0. - For each
kfrom 1 ton - 1, compute the three candidatesugly[i2] * 2,ugly[i3] * 3andugly[i5] * 5. - Store the smallest candidate in
ugly[k]. - Advance each pointer whose candidate equals
ugly[k]. More than one pointer can move in the same step. - Return
ugly[n - 1].
Step-by-step example
n = 10
- Start with
ugly = [1]and all three pointers on index 0. The candidates are 2, 3 and 5. - 2 is smallest, so
ugly[1] = 2andi2moves to index 1. Candidates become 4, 3, 5, sougly[2] = 3andi3moves. - Next come 4 (from 2 x 2) and 5 (from 1 x 5), moving
i2and theni5. - At k = 5 the candidates are 3 x 2 = 6 and 2 x 3 = 6. The value 6 is written once and both
i2andi3advance. - The pattern continues with 8, 9, 10 (a tie between 5 x 2 and 2 x 5) and 12.
- 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]1class Solution {
2 public int nthUglyNumber(int n) {
3 long[] ugly = new long[n];
4 ugly[0] = 1;
5 int i2 = 0, i3 = 0, i5 = 0;
6 for (int k = 1; k < n; k++) {
7 long next2 = ugly[i2] * 2, next3 = ugly[i3] * 3, next5 = ugly[i5] * 5;
8 ugly[k] = Math.min(next2, Math.min(next3, next5));
9 if (ugly[k] == next2) i2++;
10 if (ugly[k] == next3) i3++;
11 if (ugly[k] == next5) i5++;
12 }
13 return (int) ugly[n - 1];
14 }
15}1class Solution {
2public:
3 int nthUglyNumber(int n) {
4 vector<long long> ugly(n, 1);
5 int i2 = 0, i3 = 0, i5 = 0;
6 for (int k = 1; k < n; k++) {
7 long long next2 = ugly[i2] * 2, next3 = ugly[i3] * 3, next5 = ugly[i5] * 5;
8 ugly[k] = min({next2, next3, next5});
9 if (ugly[k] == next2) i2++;
10 if (ugly[k] == next3) i3++;
11 if (ugly[k] == next5) i5++;
12 }
13 return (int)ugly[n - 1];
14 }
15};Time and space complexity
O(n)
Each of the n - 1 iterations does a constant amount of work: three multiplications, a minimum and up to three pointer moves.
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
elifwhen 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.