Super Ugly Number

Medium · Heap & Counting · Array · Math · Dynamic Programming · Heap (Priority Queue)

Problem

A super ugly number is a positive integer whose prime factors all appear in a given list primes. The number 1 counts as super ugly.

Given n and primes, return the n-th super ugly number in increasing order. The answer fits in a signed 32-bit integer.

Examples

Input: n = 6, primes = [3,5]
Output: 25

The sequence is 1, 3, 5, 9, 15, 25.

Input: n = 1, primes = [7]
Output: 1

The first super ugly number is always 1.

Input: n = 12, primes = [2,7,13,19]
Output: 32

The sequence is 1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32.

Constraints

Approaches

Follow-up

The pointer idea is a k-way merge of the lists ugly · p. The use cases count the super ugly numbers up to a limit and test a single number.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…