Ugly Number II Problem
Description
LeetCode Problem 264.
An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.
Given an integer n, return the n^th ugly number.
Example 1:
Input: n = 10
Output: 12
Explanation: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers.
Example 2:
Input: n = 1
Output: 1
Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.
Constraints:
- 1 <= n <= 1690
Solution
Approach: Dynamic Programming with Three Pointers
Testing every integer with "is it ugly?" is far too slow: the 1690th ugly number is above two billion. Instead, build the ugly numbers in increasing order.
Every ugly number other than 1 is a smaller ugly number times 2, 3 or 5. So the next one is the smallest value of the form ugly[j] * 2, ugly[j] * 3 or ugly[j] * 5 that is larger than the last one we have.
Keep three pointers p2, p3, p5. p2 is the smallest index whose number times 2 is not in the list yet (the same for 3 and 5). Start with ugly[0] = 1 and all pointers at 0. Then for each i from 1 to n - 1:
- Compute
next2 = ugly[p2] * 2,next3 = ugly[p3] * 3,next5 = ugly[p5] * 5. - Set
ugly[i]to the smallest of the three. - Advance every pointer whose candidate equals
ugly[i]. Using separateifs (notelse if) is the key detail:6is both2 * 3and3 * 2, and advancing only one pointer would add6twice.
Complexity: O(n) time and O(n) space for the list.
class Solution:
def nthUglyNumber(self, n: int) -> int:
ugly = [1] * n # ugly[i] is the (i + 1)-th ugly number
# p2, p3, p5: the smallest index whose number times 2 (3, 5) is not in the list yet.
p2 = p3 = p5 = 0
for i in range(1, n):
next2, next3, next5 = ugly[p2] * 2, ugly[p3] * 3, ugly[p5] * 5
ugly[i] = min(next2, next3, next5)
# Advance every pointer that produced this value, so duplicates like 6 = 2*3 = 3*2 are skipped.
if ugly[i] == next2:
p2 += 1
if ugly[i] == next3:
p3 += 1
if ugly[i] == next5:
p5 += 1
return ugly[n - 1]
Now write it from memory
Close the write-up and solve it yourself against the tests.