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 - Optimal Solution INPUT Find nth super ugly number n = 12 Primes Array: 2 7 13 19 [0] [1] [2] [3] Super ugly numbers have prime factors ONLY from the given primes array Examples: 1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32... ALGORITHM STEPS 1 Initialize ugly[0]=1, pointers=[0,0,0,0] 2 Generate Candidates ugly[ptr[i]] * primes[i] 3 Select Minimum Next ugly = min(candidates) 4 Update Pointers Increment matching ptrs Sequence Generation: i=1: ugly[1] = 2 i=2: ugly[2] = 4 i=3: ugly[3] = 7 ... i=11: ugly[11] = 28 i=12: ugly[12] = 32 FINAL RESULT 12th Super Ugly: 32 Verification: 32 = 2 x 2 x 2 x 2 x 2 32 = 2^5 First 12 Super Ugly Numbers: 1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32 OK - Verified Key Insight: Use multiple pointers (one per prime) to track which ugly number each prime should multiply next. The minimum product becomes the next super ugly number. This avoids duplicates and maintains sorted order. Time: O(n * k) where k = number of primes. Space: O(n + k). TutorialsPoint - Super Ugly Number | Optimal Multi-Pointer Solution
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