Call a positive whole number ugly when 2, 3 and 5 are the only primes that divide it. So 12 = 2 × 2 × 3 is ugly, while 14 = 2 × 7 is not. The number 1 has no prime factors at all, and it counts as the first ugly number.
Given n, list the ugly numbers from smallest to largest and return the one in position n (counting from 1).
Example 1
Input: n = 7 Output: 8 Why: the ugly numbers start 1, 2, 3, 4, 5, 6, 8; 7 is skipped
2 more examples and the constraints
Example 2
Input: n = 15 Output: 24 Why: after 8 come 9, 10, 12, 15, 16, 18, 20 and then 24
Example 3
Input: n = 1 Output: 1 Why: 1 is the first ugly number
Constraints
- 1 ≤ n ≤ 1,690
- The answer fits in a signed 32-bit integer (the 1,690th is 2,123,366,400)
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Min-heap of candidatesO(n log n)
- Three pointersO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n = 1,690 | Verdict |
|---|---|---|---|
| Min-heap of candidates | O(n log n) | Passes; extra log factor | |
| Three pointers | O(n) | Best; simple and linear |
n = position of the ugly number asked for. Checking every whole number in turn would need over two billion checks.
Edge cases to test
- n = 1. The answer is 1 itself: the loop does not run.
- Ties between streams. 6, 10, 15, 30 come from two or three streams. Move every pointer that produced the value, or it appears twice.
- The largest n. n = 1,690 gives 2,123,366,400, close to the 32-bit limit. Candidates can go past it, so compute them in 64-bit.
- Skipped primes. 7, 11, 13, 14 never appear; the method never builds them, so no check is needed.
Common mistakes
- Using if/else to move the pointers, so a tied value like 6 is added twice.
- Starting the sequence at 2 and forgetting that 1 counts as the first ugly number.
- Multiplying in 32-bit ints near n = 1,690, so a candidate overflows and becomes negative.
How to talk through it
- 1Clarify. Is 1 ugly? Is n counted from 1? What is the largest n?
- 2Reject the scan. Testing every number reaches two billion; most numbers are not ugly. Generate only ugly ones.
- 3Offer the heap. Pop the smallest, push its three multiples, skip repeats. O(n log n).
- 4Merge three streams. Three pointers into the list itself give the next number in O(1); move every pointer on a tie.
- 5Test out loud. Walk n = 7 by hand, then mention n = 1 and the 32-bit edge at n = 1,690.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?