101 Logo
onenoughtone

Problem Statement

Prime Factor Sequence

You're working on a mathematical sequence generator that produces numbers with specific prime factorization properties.

An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.

Given an integer n, return the nth ugly number in the sequence, where 1 is the first ugly number.

Examples

Example 1:

Input: n = 10
Output: 12
Explanation: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers.

Example 2:

Input: n = 1
Output: 1
Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.

Constraints

  • 1 <= n <= 1690

Problem Breakdown

To solve this problem, we need to:

  1. Every ugly number (except 1) can be generated by multiplying a previous ugly number by either 2, 3, or 5
  2. We can use dynamic programming to generate the sequence of ugly numbers
  3. To avoid duplicates, we need to keep track of which previous ugly numbers have been multiplied by 2, 3, and 5
  4. The key insight is to maintain three pointers to track which previous ugly numbers to multiply by 2, 3, and 5
  5. A min heap can also be used to efficiently find the next ugly number in the sequence
  6. The problem can be solved in O(n) time and O(n) space
ProblemSolutionCode
101 Logo
onenoughtone