Ugly Number II - Problem
An ugly number is a fascinating mathematical concept - it's a positive integer whose only prime factors are 2, 3, and 5. In other words, ugly numbers can only be formed by multiplying powers of 2, 3, and 5 together!
The sequence starts as: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12...
Notice how 7 is missing (it's prime), 11 is missing (also prime), and 14 is missing (contains factor 7).
Your task: Given an integer n, return the nth ugly number in this sequence.
Goal: Efficiently generate the sequence of ugly numbers and find the nth one.
Input & Output
example_1.py โ Basic Case
$
Input:
n = 10
โบ
Output:
12
๐ก Note:
The first 10 ugly numbers are [1, 2, 3, 4, 5, 6, 8, 9, 10, 12]. The 10th ugly number is 12.
example_2.py โ Small Case
$
Input:
n = 1
โบ
Output:
1
๐ก Note:
The first ugly number is 1, which by definition has no prime factors and is considered ugly.
example_3.py โ Medium Case
$
Input:
n = 15
โบ
Output:
24
๐ก Note:
The sequence continues: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]. The 15th ugly number is 24 = 2ยณ ร 3.
Visualization
Tap to expand
Understanding the Visualization
1
Factory Setup
Three machines start processing the first ugly number (1)
2
Generate Candidates
Machine-2 produces 2, Machine-3 produces 3, Machine-5 produces 5
3
Pick Minimum
Choose smallest output (2) as next ugly number
4
Advance Production
Machine-2 moves to next input, continues generating sequence
Key Takeaway
๐ฏ Key Insight: Every ugly number (except 1) comes from multiplying a smaller ugly number by 2, 3, or 5. Using three pointers eliminates redundant calculations and generates the sequence efficiently in O(n) time.
Time & Space Complexity
Time Complexity
O(n)
We generate exactly n ugly numbers, each in constant time
โ Linear Growth
Space Complexity
O(n)
We store all n ugly numbers in an array
โก Linearithmic Space
Constraints
- 1 โค n โค 1690
- The answer is guaranteed to fit in a 32-bit signed integer
- All ugly numbers must be positive integers
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code