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
๐Ÿญ The Ugly Number FactoryMachine ร—2Input: ugly[i2]Output: ร—2Machine ร—3Input: ugly[i3]Output: ร—3Machine ร—5Input: ugly[i5]Output: ร—5Ugly Numbers Queue:123456?84 ร— 293 ร— 3102 ร— 5MIN8Always pick the minimum output to maintain ascending order
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

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

We store all n ugly numbers in an array

n
2n
โšก 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
Asked in
Google 42 Amazon 38 Microsoft 35 Meta 28 Apple 22
142.5K Views
High Frequency
~18 min Avg. Time
3.2K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen