Problem Description
A super ugly number is a positive integer whose prime factors are in the given array primes. Given an integer n and an array of primes, return the nth super ugly number. Note that 1 is considered a super ugly number since it has no prime factors.
Key Insights
- We need to generate super ugly numbers in increasing order.
- This problem is an extension of the Ugly Number II problem but with a customizable list of primes.
- Dynamic Programming (DP) can be used by maintaining an array of already computed super ugly numbers.
- Use multiple pointers (one for each prime) to generate new candidates.
- In each step, multiply the current DP values by each prime using the pointers, then choose the smallest candidate to ensure the sequence is ordered.
- Increment pointers for all primes that reach the candidate to avoid duplicate numbers.
Space and Time Complexity
Time Complexity: O(n * k), where n is the number of super ugly numbers to generate and k is the number of primes. Space Complexity: O(n + k) for the DP array and the pointer array.
Solution
We implement a dynamic programming solution using multiple pointers. We maintain a DP array where dp[i] holds the ith super ugly number. For each prime in primes, an index pointer tracks which element in dp should be multiplied next by that prime. In each iteration, we calculate the next candidate candidate numbers from the current pointers and choose the smallest one as the next super ugly number. Any pointer that contributes to this number is incremented so that duplicate multiplications are avoided. This efficiently generates the sequence up to the nth super ugly number.
Code Solutions
Below are code solutions in Python, JavaScript, C++, and Java.