Super Ugly Number — LeetCode 313 Python Solution

MediumArrayMathDynamic Programming
Problem
#313
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

Python
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

MeasureComplexity
TimeO(n \times m \times \log (n \times m))
SpaceO(n \times m) auxiliary

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

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 \times m \times \log (n \times m)).
What is the space complexity of LeetCode 313. Super Ugly Number?
The Python solution on this page uses O(n \times 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.

Get Stealth Interview