Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
A super ugly number is a positive integer whose prime factors are in the array primes.
Given an integer n and an array of integers primes, return the nth super ugly number.
The nth super ugly number is guaranteed to fit in a 32-bit signed integer.
Example 1:
Input: n = 12, primes = [2,7,13,19] Output: 32 Explanation: [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12 super ugly numbers given primes = [2,7,13,19].
Example 2:
Input: n = 1, primes = [2,3,5] Output: 1 Explanation: 1 has no prime factors, therefore all of its prime factors are in the array primes = [2,3,5].
Constraints:
1 <= n <= 1051 <= primes.length <= 1002 <= primes[i] <= 1000primes[i] is guaranteed to be a prime number.primes are unique and sorted in ascending order.Problem summary: A super ugly number is a positive integer whose prime factors are in the array primes. Given an integer n and an array of integers primes, return the nth super ugly number. The nth super ugly number is guaranteed to fit in a 32-bit signed integer.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Math · Dynamic Programming
12 [2,7,13,19]
1 [2,3,5]
ugly-number-ii)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #313: Super Ugly Number
class Solution {
public int nthSuperUglyNumber(int n, int[] primes) {
PriorityQueue<Integer> q = new PriorityQueue<>();
q.offer(1);
int x = 0;
while (n-- > 0) {
x = q.poll();
while (!q.isEmpty() && q.peek() == x) {
q.poll();
}
for (int k : primes) {
if (k <= Integer.MAX_VALUE / x) {
q.offer(k * x);
}
if (x % k == 0) {
break;
}
}
}
return x;
}
}
// Accepted solution for LeetCode #313: Super Ugly Number
func nthSuperUglyNumber(n int, primes []int) (x int) {
q := hp{[]int{1}}
for n > 0 {
n--
x = heap.Pop(&q).(int)
for _, k := range primes {
if x <= math.MaxInt32/k {
heap.Push(&q, k*x)
}
if x%k == 0 {
break
}
}
}
return
}
type hp struct{ sort.IntSlice }
func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) }
func (h *hp) Pop() any {
a := h.IntSlice
v := a[len(a)-1]
h.IntSlice = a[:len(a)-1]
return v
}
# Accepted solution for LeetCode #313: Super Ugly Number
class Solution:
def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
q = [1]
x = 0
mx = (1 << 31) - 1
for _ in range(n):
x = heappop(q)
for k in primes:
if x <= mx // k:
heappush(q, k * x)
if x % k == 0:
break
return x
// Accepted solution for LeetCode #313: Super Ugly Number
struct Solution;
use std::cmp::Reverse;
use std::collections::BinaryHeap;
use std::collections::HashSet;
impl Solution {
fn nth_super_ugly_number(mut n: i32, primes: Vec<i32>) -> i32 {
let mut queue: BinaryHeap<Reverse<i32>> = BinaryHeap::new();
let mut visited: HashSet<i32> = HashSet::new();
queue.push(Reverse(1));
while n > 1 {
let min = queue.pop().unwrap().0;
for &x in &primes {
if let Some(y) = x.checked_mul(min) {
if visited.insert(y) {
queue.push(Reverse(y));
}
}
}
n -= 1;
}
queue.pop().unwrap().0
}
}
#[test]
fn test() {
let n = 12;
let primes = vec![2, 7, 13, 19];
let res = 32;
assert_eq!(Solution::nth_super_ugly_number(n, primes), res);
}
// Accepted solution for LeetCode #313: Super Ugly Number
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #313: Super Ugly Number
// class Solution {
// public int nthSuperUglyNumber(int n, int[] primes) {
// PriorityQueue<Integer> q = new PriorityQueue<>();
// q.offer(1);
// int x = 0;
// while (n-- > 0) {
// x = q.poll();
// while (!q.isEmpty() && q.peek() == x) {
// q.poll();
// }
// for (int k : primes) {
// if (k <= Integer.MAX_VALUE / x) {
// q.offer(k * x);
// }
// if (x % k == 0) {
// break;
// }
// }
// }
// return x;
// }
// }
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: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
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.