#313
Super Ugly Number
MediumArrayMathDynamic ProgrammingHeap (Min-Heap for efficient extraction of minimum values)Dynamic Programming (for understanding how to build up solutions from smaller subproblems)
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log k) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n log k)Space O(n)
Instead of generating all super ugly numbers, we can use a min-heap to efficiently find the next super ugly number. This allows us to keep track of the smallest number generated from the primes without generating all combinations.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a min-heap and add the first super ugly number (1).
- 2Step 2: Use a set to track the numbers we've added to the heap to avoid duplicates.
- 3Step 3: Extract the smallest number from the heap, and for each prime, multiply it with the smallest number and add it back to the heap if it hasn't been added before.
- 4Step 4: Repeat until we extract the nth super ugly number.
solution.py15 lines
1# Full working Python code
2import heapq
3class Solution:
4 def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
5 heap = [1]
6 seen = {1}
7 ugly = 0
8 for _ in range(n):
9 ugly = heapq.heappop(heap)
10 for prime in primes:
11 next_ugly = ugly * prime
12 if next_ugly not in seen:
13 seen.add(next_ugly)
14 heapq.heappush(heap, next_ugly)
15 return uglyℹ
Complexity note: The time complexity is O(n log k) where k is the number of primes. Each time we extract the minimum from the heap, it takes log k time, and we do this n times.
- 1Using a min-heap allows us to efficiently find the next super ugly number without generating all combinations.
- 2Tracking seen numbers prevents duplicates and ensures we only add unique products to the heap.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.