Problem
An ugly number is a positive integer whose prime factors are limited to2, 3, and 5.
Given an integer n, return the nth * ugly number*.
Examples
Constraints
- 1 <= n <= 1690
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 264 with 20 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 264 # by problem number
lcpy gen -s ugly_number_ii # by problem name
2, 3, and 5.
Given an integer n, return the nth * ugly number*.
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.
Input: n = 1
Output: 1
Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.
class Solution:
# Time: O(n)
# Space: O(n)
def nth_ugly_number(self, n: int) -> int:
ugly = [0] * n
ugly[0] = 1
i2 = i3 = i5 = 0
for i in range(1, n):
next2, next3, next5 = ugly[i2] * 2, ugly[i3] * 3, ugly[i5] * 5
nxt = min(next2, next3, next5)
ugly[i] = nxt
if nxt == next2:
i2 += 1
if nxt == next3:
i3 += 1
if nxt == next5:
i5 += 1
return ugly[n - 1]
| Time | Space |
|---|---|
| O(n) | O(n) |