Skip to content
Problem 313 · LeetCode 313(opens in a new tab)

Super Ugly Number

MediumDynamic programming

A super ugly number is a positive whole number whose prime factors all come from a given list, primes. The number 1 counts too, since it has no prime factors.

Given n and primes, list these numbers in increasing order starting from 1, and return the one in position n. The answer always fits in a 32-bit signed integer.

Example 1

Input:  n = 7, primes = [3, 5, 7]
Output: 21
Why:    the sequence starts 1, 3, 5, 7, 9, 15, 21
2 more examples and the constraints

Example 2

Input:  n = 1, primes = [2, 11]
Output: 1
Why:    1 is always the first one

Example 3

Input:  n = 6, primes = [2, 5]
Output: 10
Why:    1, 2, 4, 5, 8, 10

Constraints

  • 1 ≤ n ≤ 100,000
  • 1 ≤ length of primes ≤ 100
  • Each entry of primes is a prime between 2 and 1,000
  • primes has no repeats and is sorted in increasing order

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Min-heap with a seen setO(n·k log(n·k))
  2. One pointer per primeO(n·k)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = 100,000 and 100 primesVerdict
Min-heap with a seen setO(n·k log(n·k))
Works; heavy on memory
One pointer per primeO(n·k)
Best; no heap, no set

n = which super ugly number to return, k = how many primes.

Edge cases to test

  • n = 1. The answer is 1, whatever the primes are.
  • One prime only. With [3], the answers are powers of 3: the 20th is 1,162,261,467.
  • A product made two ways. 15 = 3 × 5 = 5 × 3. Move both pointers, or 15 shows up twice.
  • Products past 32 bits. The answer fits, but a candidate like 1,000 × ugly[idx] may not. Use 64-bit math.

Common mistakes

  • Moving only the first pointer that matches the minimum, which stores repeats.
  • Forgetting that 1 is the first super ugly number.
  • Computing prime × ugly[idx] in a 32-bit int, which overflows near the limit.

How to talk through it

  1. 1Clarify. Does 1 count? Are the primes sorted and distinct? Does the answer fit in 32 bits?
  2. 2Give the heap. Pop the smallest, push it times every prime, skip repeats with a set. Say its memory cost.
  3. 3Spot the structure. Each number is an earlier one times a prime, so the answer list feeds itself.
  4. 4Code the pointers. One pointer per prime; take the minimum product and advance every pointer that hit it.
  5. 5Test out loud. Run n = 1 and Example 1, where 15 and 21 are each made twice.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?