MediumNo. 0264
Ugly Number II — LeetCode 264 Python Solution
- Pattern
- Heap / Priority Queue
- Topics
- Hash Table, Math, Dynamic Programming, Heap (Priority Queue)
- Reading time
- 2 min
- Source
- leetcode.com
The problem
An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. Given an integer n, return the nth ugly number.
Example
- 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.
Python solution
class Solution:
def nthUglyNumber(self, n: int) -> int:
h = [1]
vis = {1}
ans = 1
for _ in range(n):
ans = heappop(h)
for v in [2, 3, 5]:
nxt = ans * v
if nxt not in vis:
vis.add(nxt)
heappush(h, nxt)
return ansComplexity
- Time
- O(n)
- Space · auxiliary
- O(n)
Pattern: Heap / Priority Queue
Keep only the best k elements, or always pull the smallest, in log time. LeetCode 264. Ugly Number II is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.
The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0263 | Ugly Number | Easy |
| 0996 | Number of Squareful Arrays | Hard |
| 1994 | The Number of Good Subsets | Hard |
| 2019 | The Score of Students Solving Math Expression | Hard |
| 2266 | Count Number of Texts | Medium |
| 2597 | The Number of Beautiful Subsets | Medium |
Frequently asked questions
- How hard is LeetCode 264. Ugly Number II?
LeetCode 264. Ugly Number II is rated Medium on LeetCode.
- What is the time complexity of LeetCode 264. Ugly Number II?
The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 264. Ugly Number II?
The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 264. Ugly Number II cover?
LeetCode 264. Ugly Number II is tagged Hash Table, Math, Dynamic Programming and Heap (Priority Queue) on LeetCode.