Solution: Super Ugly Number
Discover how to solve the nth super ugly number problem by applying a k-way merge strategy combined with a min heap. Understand how to dynamically generate and track super ugly numbers using prime factors, optimizing for time and space complexity. This lesson reinforces practical coding techniques useful for coding interviews.
We'll cover the following...
Statement
Given an integer n and an array of distinct prime numbers primes, return the n-th super ugly number. A super ugly number is a positive integer whose only prime factors are from a given array primes.
The n-th super ugly number is guaranteed to fit within a 32-bit signed integer.
Constraints:
nprimes.lengthprimes[i]primes[i]is guaranteed to be a prime number.All the values of
primesare unique and sorted in an ascending order.
Solution
The problem is solved using a k-way merge approach combined with a min heap, ensuring that numbers are generated in strictly increasing order while avoiding redundancy. Instead of precomputing all possible multiples of the given prime factors, we dynamically construct the list by continuously tracking and merging only the smallest valid values at each step. This prevents unnecessary computations and avoids storing large sets of numbers in advance.
The algorithm begins with a list containing only
The steps of the algorithm are as follows:
Create an array,
ugly, and initialize it with1, as1is always the first super ugly number.Create a
minHeapand push the first multiple of each prime (which is the prime itself) into the heap as(prime, prime, 0), where:The first value represents the next potential ugly number.
The second value keeps track of the prime factor that generated the next potential ugly number.
The third value is the index of the ugly number multiplied by the prime to generate the potential ugly number. It helps us track which ugly number was last multiplied by the prime to correctly compute the next multiple.
Iterate until
nsuper ugly numbers are found:Extract the smallest number (
nextUgly) from the heap. We also extract the correspondingprimeandindexfrom the heap.If
nextUglyis not a duplicate (since multiple primes can generate the same number), append it tougly.Compute the next multiple (number) by multiplying the extracted
primeand the next number inuglythat comes after the last number used for thisprime.Push the new tuple
(prime * ugly[index + 1], prime, index + 1)back into the heap.
The
n-th super ugly number is the last element in theuglylist. Return this value as the final result.
Let’s look at the following illustration to get a better understanding of the solution:
Let’s look at the code for the algorithm we just discussed.
Time complexity
The time complexity of this solution is
Space complexity
The above solution’s space complexity is ugly array and maintain a heap of size