Super Ugly Number

The nth number whose prime factors lie in a given list — k-way merge of multiples.

Medium
Time O(n * k) Space O(n + k)
LeetCode
4 min read
k-way-merge dp heaps

Problem#

A super ugly number has all prime factors in the given list primes. Return the nth such number (1-indexed; 1 counts).

Examples#

  • n = 12, primes = [2,7,13,19]32

Constraints#

  • 1 <= n <= 10^5, 1 <= primes.length <= 100.

Approach#

DP with k pointers: dp[i] is the i-th super ugly. For each prime p, maintain a pointer idx[p] such that the next multiple is p * dp[idx[p]]. Pick the minimum across primes; advance every pointer whose product equals that minimum (to dedup).

Solution#

Super Ugly Number
class Solution {
public:
int nthSuperUglyNumber(int n, vector<int>& primes) {
int k = primes.size();
vector<int> dp(n);
vector<int> idx(k, 0);
dp[0] = 1;
for (int i = 1; i < n; ++i) {
int next = INT_MAX;
for (int j = 0; j < k; ++j)
next = min(next, primes[j] * dp[idx[j]]);
dp[i] = next;
for (int j = 0; j < k; ++j)
if (primes[j] * dp[idx[j]] == next) ++idx[j];
}
return dp[n - 1];
}
};

Editorial#

Each pointer idx[j] represents “the next dp-entry we’d multiply by primes[j]”. The frontier of k candidates is the heads of k merge streams. Advancing every pointer with the same candidate value dedups (e.g. 2*3 == 3*2 produces 6 only once).

Complexity#

  • Time: O(n * k).
  • Space: O(n + k).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.