Mutating counts without cleanup
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Move from brute-force thinking to an efficient approach using hash map strategy.
An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.
Given an integer n, return the nth ugly number.
Example 1:
Input: n = 10 Output: 12 Explanation: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers.
Example 2:
Input: n = 1 Output: 1 Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.
Constraints:
1 <= n <= 1690Problem summary: An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. Given an integer n, return the nth ugly number.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Hash Map · Math · Dynamic Programming
10
1
merge-k-sorted-lists)count-primes)ugly-number)perfect-squares)super-ugly-number)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #264: Ugly Number II
class Solution {
public int nthUglyNumber(int n) {
Set<Long> vis = new HashSet<>();
PriorityQueue<Long> q = new PriorityQueue<>();
int[] f = new int[] {2, 3, 5};
q.offer(1L);
vis.add(1L);
long ans = 0;
while (n-- > 0) {
ans = q.poll();
for (int v : f) {
long next = ans * v;
if (vis.add(next)) {
q.offer(next);
}
}
}
return (int) ans;
}
}
// Accepted solution for LeetCode #264: Ugly Number II
func nthUglyNumber(n int) int {
h := IntHeap([]int{1})
heap.Init(&h)
ans := 1
vis := map[int]bool{1: true}
for n > 0 {
ans = heap.Pop(&h).(int)
for _, v := range []int{2, 3, 5} {
nxt := ans * v
if !vis[nxt] {
vis[nxt] = true
heap.Push(&h, nxt)
}
}
n--
}
return ans
}
type IntHeap []int
func (h IntHeap) Len() int { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x any) {
*h = append(*h, x.(int))
}
func (h *IntHeap) Pop() any {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
# Accepted solution for LeetCode #264: Ugly Number II
class Solution:
def nthUglyNumber(self, n: int) -> int:
h = [1]
vis = {1}
ans = 1
for _ in range(n):
ans = heappop(h)
for v in [2, 3, 5]:
nxt = ans * v
if nxt not in vis:
vis.add(nxt)
heappush(h, nxt)
return ans
// Accepted solution for LeetCode #264: Ugly Number II
struct Solution;
impl Solution {
fn nth_ugly_number(n: i32) -> i32 {
let n = n as usize;
let mut ugly: Vec<i32> = vec![1];
let mut i = 0;
let mut j = 0;
let mut k = 0;
while ugly.len() <= n {
let min = vec![ugly[i] * 2, ugly[j] * 3, ugly[k] * 5]
.into_iter()
.min()
.unwrap();
ugly.push(min);
if ugly[i] * 2 == min {
i += 1;
}
if ugly[j] * 3 == min {
j += 1;
}
if ugly[k] * 5 == min {
k += 1;
}
}
ugly[n - 1]
}
}
#[test]
fn test() {
let n = 10;
let res = 12;
assert_eq!(Solution::nth_ugly_number(n), res);
}
// Accepted solution for LeetCode #264: Ugly Number II
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #264: Ugly Number II
// class Solution {
// public int nthUglyNumber(int n) {
// Set<Long> vis = new HashSet<>();
// PriorityQueue<Long> q = new PriorityQueue<>();
// int[] f = new int[] {2, 3, 5};
// q.offer(1L);
// vis.add(1L);
// long ans = 0;
// while (n-- > 0) {
// ans = q.poll();
// for (int v : f) {
// long next = ans * v;
// if (vis.add(next)) {
// q.offer(next);
// }
// }
// }
// return (int) ans;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.