Ugly Number II

Hard

Topics
Hash TableMathDynamic ProgrammingHeap

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. (The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, ... begins with 1.)

Example 1

1021324354658697108129
Every ugly number is some earlier ugly number times 2, 3 or 5, so the sequence is built forwards from three moving pointers rather than by testing each integer. The 10th is 12.
Cells are the ugly numbers in order; the index is 1-based in the statement.
Input:  n = 10
Output: 12

Example 2

10
Input:  n = 1
Output: 1

Constraints

  • 1 <= n <= 1690
Editorial — intuition, approach, complexity and pitfalls

Intuition

Every ugly number after the first is an earlier ugly number multiplied by 2, 3 or 5. So the sequence can be generated by merging three streams — all ugly numbers doubled, all tripled, all quintupled — which are each already sorted.

Three index pointers do the merge without a heap. i2 marks the earliest ugly number whose double has not been emitted yet, and similarly for 3 and 5. The next ugly number is the minimum of the three candidates, and then every pointer whose candidate equals that minimum advances.

Advancing all matching pointers is the whole correctness argument. 6 is reachable as 2×3 and as 3×2; if only one pointer moved, 6 would be emitted twice and the sequence would be wrong from that point on.

Approach

  1. Start the sequence at 1 with all three pointers at index 0.
  2. Compute the three candidates 2×ugly[i2], 3×ugly[i3], 5×ugly[i5].
  3. Append the minimum.
  4. Advance every pointer whose candidate equals that minimum — three separate if tests, not elif.
  5. Return the n-th entry.

Dry Run

  i   2*ugly[i2]  3*ugly[i3]  5*ugly[i5]  chosen  pointers advanced
  1   2           3           5           2       i2
  2   4           3           5           3       i3
  3   4           6           5           4       i2
  4   6           6           5           5       i5
  5   6           6           10          6       i2 and i3     <- both!
  6   8           9           10          8       i2
  7   10          9           10          9       i3
  8   10          12          10          10      i2 and i5     <- both!
  9   12          12          15          12      i2 and i3
  10  16          15          15          15      i3 and i5

sequence [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15]

the 11th ugly number is 15

step 5 is the one that matters: 6 is both 2*3 and 3*2, so advancing only one
pointer would emit 6 again on the next step.

Complexity

  • Time — O(n): constant work per emitted number.
  • Space — O(n) for the sequence, which is needed because later candidates index back into it.
  • A min-heap with a dedup set is the other standard answer: O(n log n) time and O(n) space, and it generalises to an arbitrary set of factors — which the three-pointer version does not without becoming a k-way merge.

Common Pitfalls

  • Using elif for the pointer advances. Measured: it first diverges at n = 7, because 6 gets emitted twice and the sequence shifts.
  • Comparing against the recomputed product rather than the stored candidate. After i2 advances, 2×ugly[i2] is a different number, so the remaining equality tests must use the values captured before any pointer moved.
  • Testing each number from 1 upward for uglyness by dividing out 2, 3 and 5. That is correct and O(answer · log answer) — and the 1690th ugly number is 2,123,366,400, so it never finishes.
  • Starting the sequence at 2, or treating 1 as not ugly. 1 has no prime factors outside the set, so it is the first term.
  • Using a heap without deduplication, which emits every number once per factorisation.
  • Overflow. The 1690th ugly number exceeds 2³¹, so the sequence must be held in a 64-bit type in Java and C++.

Full Solution — all languages

class Solution:
    def nthUglyNumber(self, n):
        ugly = [1] * n
        i2 = i3 = i5 = 0
        for i in range(1, n):
            next2, next3, next5 = ugly[i2] * 2, ugly[i3] * 3, ugly[i5] * 5
            ugly[i] = min(next2, next3, next5)
            if ugly[i] == next2:
                i2 += 1
            if ugly[i] == next3:
                i3 += 1
            if ugly[i] == next5:
                i5 += 1
        return ugly[n - 1]
Asked at Paytm
SensAI
Beta
Tap the mic to stop voice mode