MediumNo. 0313

Super Ugly Number — LeetCode 313 Python Solution

Topics
Array, Math, Dynamic Programming
Reading time
2 min

The problem

A super ugly number is a positive integer whose prime factors are in the array primes. Given an integer n and an array of integers primes, return the nth 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].

Python solution

PythonSolution
class Solution:
    def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
        q = [1]
        x = 0
        mx = (1 << 31) - 1
        for _ in range(n):
            x = heappop(q)
            for k in primes:
                if x <= mx // k:
                    heappush(q, k * x)
                if x % k == 0:
                    break
        return x

Complexity

Time
O(n × m × log (n × m))
Space · auxiliary
O(n × m)

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 313. Super Ugly Number is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0368Largest Divisible SubsetMedium
0396Rotate FunctionMedium
0486Predict the WinnerMedium
0553Optimal DivisionMedium
0805Split Array With Same AverageHard
0877Stone GameMedium

Frequently asked questions

How hard is LeetCode 313. Super Ugly Number?

LeetCode 313. Super Ugly Number is rated Medium on LeetCode.

What is the time complexity of LeetCode 313. Super Ugly Number?

The Python solution on this page runs in O(n × m × log (n × m)).

What is the space complexity of LeetCode 313. Super Ugly Number?

The Python solution on this page uses O(n × m) auxiliary space.

What topics does LeetCode 313. Super Ugly Number cover?

LeetCode 313. Super Ugly Number is tagged Array, Math and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.