↓Skip to main content
  1. LeetCode/

LeetCode 264: Ugly Number II

·2 mins· ·
LeetCode Medium Hash-Table Math Dynamic-Programming Heap-Priority-Queue
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-11-14

  • Submissions: Time Limit Exceeded ×3 → Accepted ×3

Approach
#

Every ugly number is a smaller ugly number times 2, 3 or 5. Keep pointers i2, i3, i5; the next one is min(u[i2] * 2, u[i3] * 3, u[i5] * 5), and every pointer that produced it advances, avoiding duplicates such as 6 = 2 × 3 = 3 × 2 (Linear DP Template 1).

My Attempts
#

The first three tested every integer from 1 for ugliness (the second added a seen set), but the nth ugly number can be huge, so checking one by one was too slow: three TLEs. The three-pointer version passed.

Solution
#

class Solution:
    def nthUglyNumber(self, n: int) -> int:
        u = [1]
        i2 = i3 = i5 = 0
        while len(u) < n:
            nxt = min(u[i2] * 2, u[i3] * 3, u[i5] * 5)
            u.append(nxt)
            if nxt == u[i2] * 2: i2 += 1
            if nxt == u[i3] * 3: i3 += 1
            if nxt == u[i5] * 5: i5 += 1
        return u[-1]

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • Use three separate ifs, not elif, so every matching pointer advances.
  • Testing each integer from 1 times out; the 1690th ugly number exceeds two billion.

Interview Explanation
#

Each ugly number is a smaller one times 2, 3 or 5, so three pointers mark the next to multiply; I take the smallest product and advance every pointer that matches it to avoid duplicates. Time O(n).

Related

LeetCode 187: Repeated DNA Sequences
·1 min
LeetCode Medium Hash-Table String Bit-Manipulation Sliding-Window
LeetCode 187 note: count every length-10 substring in a hash map and return those seen more than once
LeetCode 50: Pow(x, n)
·2 mins
LeetCode Medium Math Recursion
LeetCode 50 note: fast exponentiation, x^n = (x²)^(n/2) with an extra x for odd n; for negative n compute 1 / x^(-n)
LeetCode 227: Basic Calculator II
·2 mins
LeetCode Medium Math String Stack
LeetCode 227 note: read whole numbers, and at each operator apply the previous one: + and - push the number (negated for -), * and / combine with the top
LeetCode 229: Majority Element II
·2 mins
LeetCode Medium Array Hash-Table Sorting Counting
LeetCode 229 note: at most two values can exceed n / 3; Boyer-Moore keeps two candidates and a second pass verifies their counts
LeetCode 189: Rotate Array
·2 mins
LeetCode Medium Array Math Two-Pointers
LeetCode 189 note: take k %= n, then reverse three times: the whole array, the first k, and the last n - k, with O(1) extra space
LeetCode 204: Count Primes
·2 mins
LeetCode Medium Array Math Enumeration Number-Theory
LeetCode 204 note: the sieve of Eratosthenes, crossing out multiples of each prime p starting at p², with the outer loop only up to √n