โ† Back to Index

๐Ÿ“š Super Ugly Number โ€“ Java Cheat Sheet

๐Ÿ“Œ What Is It?

The problem involves finding the n-th super ugly number. A super ugly number is a positive integer whose prime factors are in a given list of primes.

This problem can be efficiently solved using a min-heap to track the smallest multiples of the primes.

๐Ÿงฑ Pattern Template

class Solution {
    public int nthSuperUglyNumber(int n, int[] primes) {
        int[] ugly = new int[n];
        ugly[0] = 1;

        // Each entry: [nextVal, prime, index_in_ugly_array]
        PriorityQueue<long[]> pq = new PriorityQueue<>(Comparator.comparingLong(a -> a[0]));

        for (int prime : primes) {
            pq.offer(new long[]{prime, prime, 0});
        }

        for (int i = 1; i < n; ) {
            long[] top = pq.poll();
            long nextVal = top[0];
            long prime = top[1];
            int idx = (int) top[2];

            if (nextVal != ugly[i - 1]) {
                ugly[i++] = (int) nextVal;
            }

            long newVal = prime * ugly[idx + 1];
            pq.offer(new long[]{newVal, prime, idx + 1});
        }

        return ugly[n - 1];
    }
}

๐Ÿ“Š Time Complexity

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example: Super Ugly Number

Input: n = 12, primes = [2,7,13,19]
Output: 32

Explanation:
- The sequence of super ugly numbers is [1, 2, 7, 13, 14, 19, 26, 28, 32, ...].
- The 12th super ugly number is 32.

๐Ÿ’ก Pro Tips