Super Ugly Number - Problem

A super ugly number is a positive integer whose only prime factors are found in a given array of primes. Think of it as building numbers using only specific "building blocks" (prime factors).

Given an integer n and an array of integers primes, your task is to find the n-th super ugly number. The sequence starts with 1 (which has no prime factors), and each subsequent number can only be formed by multiplying previous super ugly numbers with the given primes.

Example: If primes = [2, 7, 13, 19], the sequence begins: 1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32...

Your goal is to efficiently generate this sequence and return the n-th number, which is guaranteed to fit in a 32-bit signed integer.

Input & Output

example_1.py — Basic case
$ Input: n = 12, primes = [2,7,13,19]
Output: 32
💡 Note: The sequence is [1,2,4,7,8,13,14,16,19,26,28,32]. The 12th super ugly number is 32.
example_2.py — Single prime
$ Input: n = 1, primes = [2,3,5]
Output: 1
💡 Note: The first super ugly number is always 1, regardless of the primes array.
example_3.py — Small sequence
$ Input: n = 5, primes = [2,3]
Output: 8
💡 Note: The sequence is [1,2,3,4,6,8]. The 5th number would be 6, but we want the 5th index (0-based) which gives us 8.

Visualization

Tap to expand
Super Ugly Number FactoryAssembly Line 1: Prime 2×248Next: 2×4=8Assembly Line 2: Prime 7×77Next: 7×1=7Assembly Line 3: Prime 13×1313Next: 13×1=13Quality Control CenterSelect MIN(8, 7, 13) = 7🎯 Efficient CoordinationEach line works independently, quality control ensures sorted output
Understanding the Visualization
1
Setup Assembly Lines
Each prime gets its own production line that multiplies existing products
2
Generate Candidates
Each line produces its next candidate product
3
Pick Minimum
Quality control selects the smallest product from all lines
4
Advance Lines
All lines that produced the selected product move to their next position
Key Takeaway
🎯 Key Insight: By maintaining multiple production lines (pointers) and always selecting the minimum product, we generate super ugly numbers in perfect sorted order with optimal O(n×k) efficiency.

Time & Space Complexity

Time Complexity
⏱️
O(n * k)

For each of n positions, we check k primes to find minimum candidate

n
2n
Linear Growth
Space Complexity
O(n + k)

O(n) for result array and O(k) for pointers array where k is number of primes

n
2n
Linearithmic Space

Constraints

  • 1 ≤ n ≤ 106
  • 1 ≤ primes.length ≤ 100
  • 2 ≤ primes[i] ≤ 1000
  • primes[i] is guaranteed to be a prime number
  • All the values of primes are unique and sorted in ascending order
Asked in
Google 45 Facebook 32 Amazon 28 Microsoft 22
52.0K Views
Medium Frequency
~18 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen