An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.

Given an integer n, return the n-th ugly number.

For example, the first 10 ugly numbers are: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12. Note that 1 is typically treated as an ugly number.

Input & Output

Example 1 — Finding 10th Ugly Number
$ 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 — First Ugly Number
$ Input: n = 1
Output: 1
💡 Note: 1 is conventionally treated as the first ugly number.
Example 3 — Edge Case with Small n
$ Input: n = 6
Output: 6
💡 Note: The first 6 ugly numbers are: 1, 2, 3, 4, 5, 6. The 6th is 6 (which is 2 × 3).

Constraints

  • 1 ≤ n ≤ 1690

Visualization

Tap to expand
Ugly Number II: Find 10th Ugly NumberInput: n = 10n = 10Ugly Numbers (factors: 2, 3, 5 only)11st22nd33rd44th55th66th7skip87th98th109th1210thWhy these are ugly:1=1, 2=2¹, 3=3¹, 4=2², 5=5¹, 6=2×38=2³, 9=3², 10=2×5, 12=2²×37=7¹ (not ugly)Output12Answer: The 10th ugly number is 12
Understanding the Visualization
1
Input
Given n, find the nth ugly number
2
Generate
Build sequence using only factors 2, 3, 5
3
Output
Return the nth number in the sequence
Key Takeaway
🎯 Key Insight: Generate ugly numbers in order using three pointers for multiples of 2, 3, and 5
Asked in
Google 25 Amazon 20 Microsoft 15 Facebook 12
185.0K Views
Medium Frequency
~25 min Avg. Time
2.8K 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