Super Ugly Number - Problem

A super ugly number is a positive integer whose prime factors are all contained in the given 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.

Input & Output

Example 1 — 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 — Small Input
$ Input: n = 1, primes = [2,3,5]
Output: 1
💡 Note: 1 is the first super ugly number for any prime array.
Example 3 — Single Prime
$ Input: n = 5, primes = [3]
Output: 81
💡 Note: With only prime 3, the sequence is [1,3,9,27,81]. The 5th number is 81 = 3⁴.

Constraints

  • 1 ≤ n ≤ 106
  • 1 ≤ primes.length ≤ 100
  • 2 ≤ primes[i] ≤ 1000
  • primes[i] is a prime number
  • All the values of primes are unique and sorted

Visualization

Tap to expand
Super Ugly Number: Find 12th number with primes [2,7,13,19]12478131416192628321st2nd3rd4th5th6th7th8th9th10th11th12thPrime Factors Check: 32 = 2⁵ ✓ (only uses prime 2 from [2,7,13,19])Primes: [2,7,13,19]Generate: 1→2→4→7→...Result: 32Answer: 32 (the 12th super ugly number)
Understanding the Visualization
1
Input
n=12, primes=[2,7,13,19] → find 12th super ugly number
2
Generate
Build sequence: 1,2,4,7,8,13,14,16,19,26,28,32...
3
Output
12th number is 32
Key Takeaway
🎯 Key Insight: Each super ugly number is formed by multiplying an existing super ugly number with one of the given primes
Asked in
Google 45 Facebook 32 Amazon 28 Microsoft 22
89.4K Views
Medium Frequency
~25 min Avg. Time
1.6K 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