Super Ugly Number — LeetCode 313 Python Solution
- Problem
- #313
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
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
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 xComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times m \times \log (n \times m)) |
| Space | O(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.