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 - Dynamic Programming INPUT Find the nth ugly number n = 10 Target index Ugly Number Definition: Prime factors only: 2, 3, 5 2 3 5 First 10 ugly numbers: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 1 is always ugly ALGORITHM STEPS 1 Initialize dp[0]=1, pointers p2,p3,p5=0 2 Generate Candidates dp[p2]*2, dp[p3]*3, dp[p5]*5 3 Select Minimum dp[i] = min(c2, c3, c5) 4 Update Pointers Increment matching ptrs DP Table Build: i: 0 1 2 3 4 5 6 7 8 9 dp: 1 2 3 4 5 6 8 9 10 12 p2: 0 1 1 2 2 3 4 4 5 6 p3: 0 0 1 1 1 2 2 3 3 4 p5: 0 0 0 0 1 1 1 1 2 2 FINAL RESULT The 10th ugly number is: 12 Verification: 12 = 2 x 2 x 3 Only factors: 2, 3 -- OK Complete Sequence: 1 2 3 4 5 6 8 9 10 12 Time: O(n) | Space: O(n) Key Insight: Use three pointers to track which ugly numbers should be multiplied by 2, 3, and 5 next. Each new ugly number is the minimum of dp[p2]*2, dp[p3]*3, dp[p5]*5. This ensures we generate ugly numbers in sorted order without duplicates by incrementing all matching pointers. TutorialsPoint - Ugly Number II | Dynamic Programming Approach
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