The problem is to find the nth “ugly number.” In this context, ugly numbers are positive integers whose prime factors only include 2, 3, or 5. The sequence of ugly numbers starts with 1, followed by numbers such as 2, 3, 4, 5, 6, 8, and so on.
Given an integer n
, return the nth ugly number in this sequence.
Example:
n = 10
12
n
: What are the constraints for n
? (This helps to understand the efficiency required)n
?To solve this problem, we will use a dynamic programming approach involving “merging” three sequences:
uglies
containing the first ugly number, 1
.n
, find the minimum of the next multiples of 2, 3, and 5.uglies
list.uglies
array.def nthUglyNumber(n: int) -> int:
uglies = [1]
i2 = i3 = i5 = 0
for i in range(1, n):
next2, next3, next5 = uglies[i2] * 2, uglies[i3] * 3, uglies[i5] * 5
next_ugly = min(next2, next3, next5)
uglies.append(next_ugly)
if next_ugly == next2:
i2 += 1
if next_ugly == next3:
i3 += 1
if next_ugly == next5:
i5 += 1
return uglies[-1]
# Example Usage
n = 10
print(nthUglyNumber(n)) # Output: 12
1
to n
, performing constant-time operations within each iteration.n
ugly numbers.This solution should efficiently handle constraints typically given in coding problems on platforms like LeetCode.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?