Super Ugly Number Problem
Description
LeetCode Problem 313.
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 n^th super ugly number.
The n^th 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 <= 10^6
- 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.
Solution
Approach: One Pointer per Prime
Testing every integer for its prime factors is far too slow, because super ugly numbers get sparse quickly. Instead, build them in increasing order. Every super ugly number except 1 is a smaller super ugly number times one of the primes, so the next one is always the smallest product ugly[i] * p that we have not used yet.
Keep one pointer per prime:
index[j]is the position inuglyof the number thatprimes[j]should multiply next.candidates[j] = ugly[index[j]] * primes[j]is the next value that prime offers.
Start with ugly[0] = 1 and every index[j] = 0. Then, for each new position i:
ugly[i]is the smallest of the candidates.- Every prime whose candidate equals
ugly[i]moves its pointer forward one step and recomputes its candidate.
Since each pointer only moves forward through an increasing list, every product is produced in order and none is skipped.
The detail people get wrong is duplicates: with primes = [2,7,13,19], 14 comes from both 2 * 7 and 7 * 2. Advancing every pointer that produced the minimum (not just the first one) makes sure 14 appears once. The other trap is overflow: the answer fits in a 32-bit integer, but a candidate can be up to 1000 times larger, so Java and C++ store the candidates as 64-bit integers.
Complexity: O(n · k) time, where k is the length of primes: each of the n steps scans all candidates. O(n + k) space.
class Solution:
def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
ugly = [1] * n # the super ugly numbers in increasing order
k = len(primes)
index = [0] * k # index[j]: the ugly number that primes[j] multiplies next
candidates = list(primes) # candidates[j] = ugly[index[j]] * primes[j]
for i in range(1, n):
ugly[i] = min(candidates)
# Advance every prime that produced this value, so it is not added twice.
for j in range(k):
if candidates[j] == ugly[i]:
index[j] += 1
candidates[j] = ugly[index[j]] * primes[j]
return ugly[n - 1]
Now write it from memory
Close the write-up and solve it yourself against the tests.