In this Leetcode Super Ugly Number problem solution A super ugly number is a positive integer whose prime factors are in the array primes. we have given an integer n and an array of integers primes, return the nth super ugly number. The nth super ugly number is guaranteed to fit in a 32-bit signed integer.

Leetcode Super Ugly Number problem solution


Problem solution in Python.

class Solution:
def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
    heap = []
    heappush(heap,1)        
    for i in range(n - 1):
        t = heappop(heap)             
        while len(heap) > 0 and t == heap[0]   :
            heappop(heap)            
        for j in primes:                
            heappush(heap,t * j)    
    return heap[0]



Problem solution in Java.

class Solution {
    public int nthSuperUglyNumber(int n, int[] primes) {
        int m = primes.length;
        
        int[] mul = new int[m];
        
        Arrays.fill(mul, 0);
        
        int[] dp = new int[n];
        
        dp[0] = 1;
        
        for (int i = 1; i < n; i++) {
            dp[i] = Integer.MAX_VALUE;
            
            int temp1 = -1;
            
            for (int j = 0; j < m; j++) {
                int temp2 = dp[mul[j]] * primes[j];
                
                if (dp[i] > temp2) {
                    dp[i] = temp2;
                    
                    temp1 = j;
                } else if (dp[i] == temp2)
                    mul[j] = mul[j] + 1;
            }
            
            mul[temp1] = mul[temp1] + 1;
        }
        
        return dp[n - 1];
    }
}


Problem solution in C++.

class Solution {
public:
    int nthSuperUglyNumber(int n, vector<int>& primes) {
        int cur=1;
        set<int> buf(primes.begin(),primes.end());
        for(int i=1;i<n;i++)
        {
            auto itr=buf.begin();
            cur=*itr;
            buf.erase(itr);
            for(int p:primes)
            {
                if((long long)p*cur > INT_MAX)
                    continue;
                buf.insert(p*cur);
            }
        }
        return cur;
        
    }
};


Problem solution in C.

int data[1000000+5]={1};
int nthSuperUglyNumber(int n, int* primes, int primesSize) {
    int ptr[105]={0}, value[105];
    int min_value, last = 1, cnt = 1;
    memcpy(value,primes,sizeof(int)*primesSize);
    while(cnt < n)
    {
        min_value = INT_MAX;
        for(int i = 0; i < primesSize; i++)
        {
            if(value[i] <= last)
                value[i] = primes[i] * data[++ptr[i]];
            if(min_value > value[i])
                min_value = value[i];
        }
        data[cnt++] = last = min_value;
    }
    return data[n-1];
}