Leetcode 313. Super Ugly Number
A super ugly number is a positive integer whose prime factors are in the given list of primes primes
. Given an integer n
and a list of integers primes
, return the n
-th super ugly number.
Example:
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].
n
?
1 <= n <= 10^6
.primes
always contain prime numbers between 1 to 100?
primes
contain duplicates?
primes
are distinct.To solve this problem, we can use a variation of Dijkstra’s algorithm, often employed for finding the n-th ugly number in such problems. Here’s a step-by-step breakdown of the strategy:
ugly
to store the first n
super ugly numbers.primes
, initialized with the prime value itself.ugly
array.n
elements in the ugly
array.import java.util.*;
public class SuperUglyNumber {
public int nthSuperUglyNumber(int n, int[] primes) {
// Min-heap to keep track of the current minimal values.
PriorityQueue<Long> minHeap = new PriorityQueue<>();
// Set to avoid duplicate entries in the heap.
Set<Long> seen = new HashSet<>();
// Initialize the heap with primes.
for (int prime : primes) {
minHeap.add((long) prime);
seen.add((long) prime);
}
// Initialize the first ugly number.
long[] ugly = new long[n];
ugly[0] = 1;
for (int i = 1; i < n; i++) {
// Extract the smallest number from the heap.
long nextUgly = minHeap.poll();
// Store the next ugly number in our array.
ugly[i] = nextUgly;
// For every prime, calculate the new number by multiplying with next ugly number.
for (int prime : primes) {
long newUgly = nextUgly * prime;
// Add to heap only if it hasn't been seen before.
if (seen.add(newUgly)) {
minHeap.add(newUgly);
}
}
}
return (int) ugly[n - 1];
}
public static void main(String[] args) {
SuperUglyNumber solution = new SuperUglyNumber();
int n = 12;
int[] primes = {2, 7, 13, 19};
System.out.println(solution.nthSuperUglyNumber(n, primes)); // Output: 32
}
}
O(log H)
time, where H
is the size of the heap.k
be the number of primes.O(n * k * log H)
. Given that the heap size H
is approximately O(n * k)
, the complexity can be approximated to O(n * k * log(n * k))
.In summary, this approach efficiently finds the n-th super ugly number using a min-heap and avoids unnecessary duplicates through the use of a set for tracking.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?