Taro Logo

Ugly Number II

#18 Most AskedMedium
0 views
Topics:
Dynamic Programming

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.

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

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum value of $n$ that we need to support, and will it fit within a standard 32-bit signed integer?
  2. By convention, is 1 considered the first ugly number?
  3. Are ugly numbers strictly defined as positive integers whose prime factors are limited to 2, 3, and 5?
  4. If $n$ is out of bounds or invalid, how should the function behave, or can we assume $n$ will always be a valid positive integer?
  5. Should the solution return the $n$-th ugly number as a 32-bit integer, or should we use 64-bit integers (like `long` in Java/C++) to prevent potential overflow for larger values of $n$?

Brute Force Solution

Approach

Imagine we need to find a specific special number in a giant sorted sequence of numbers that only have certain allowed factors. The brute force approach checks every single whole number one by one, starting from the very beginning, to see if it qualifies.

Here's how the algorithm would work step-by-step:

  1. Start testing numbers sequentially beginning with the number one.
  2. For each number you test, check if it can be broken down using only the allowed prime factors.
  3. If a number breaks down successfully using only those allowed factors, count it as a valid special number.
  4. If it uses any other factors, throw it away and ignore it.
  5. Keep a running count of how many valid special numbers you have successfully found so far.
  6. Continue this process of checking every next number until the running count reaches the target position you were asked to find.
  7. Stop immediately and report the last valid special number you just checked once you reach your target count.

Code Implementation

def nth_ugly_number(target_position):    valid_number_count = 0    current_number = 0    # We must iterate sequentially because the sequence of ugly numbers has no arithmetic shortcut    while valid_number_count < target_position:        current_number += 1        temp_number = current_number        for prime_factor in [2, 3, 5]:            while temp_number % prime_factor == 0:                temp_number //= prime_factor        # If division completely reduces the number to one, it consists solely of allowed factors        if temp_number == 1:            valid_number_count += 1    # Halting execution guarantees we isolate the exact target index requested by the prompt    return current_number

Big(O) Analysis

Time Complexity
O(n * M) – To find the n-th ugly number, we must sequentially check every whole number starting from one up to an unknown target value M. For each candidate number, the algorithm performs repeated division to test if it can be broken down using only the allowed prime factors. Because we must test a total of M numbers sequentially until our running count reaches n, the total number of operations is proportional to n times M. As the unknown maximum value M scales unpredictably relative to n depending on the factor density, the time complexity is driven by this sequential search and division process.
Space Complexity
O(n) – To implement the step-by-step process of gathering valid special numbers up to the target position, the algorithm uses an auxiliary array of size N to store the sequential sequence of generated ugly numbers. In addition to this array, a few primitive index pointers and multiplier variables are maintained to track the state of the computation. As the target position denoted by N increases, the extra memory required by the array grows proportionally with it. Therefore, simplifying these components to Big O notation yields a total auxiliary space complexity of O(N).

Optimal Solution

Approach

Instead of checking every single number to see if it is ugly, the optimal approach builds the sequence of ugly numbers in order from smallest to largest. By using the rule that every ugly number is simply a previous ugly number multiplied by two, three, or five, we can strategically generate the next correct number every time.

Here's how the algorithm would work step-by-step:

  1. Begin with the very first ugly number, which is one.
  2. Imagine three separate tracking markers, one for each allowed multiplier of two, three, and five.
  3. Look at the numbers that would result if you multiplied the current numbers pointed to by each of the three markers.
  4. Pick the smallest of these three results to be the next official ugly number in our growing sequence.
  5. Advance the marker that contributed this winning number, since it has now done its job for that step.
  6. If any markers happen to result in the exact same value, advance all of them to avoid duplicates.
  7. Repeat this process of picking the smallest future possibility and advancing the right marker until you have built up enough numbers to reach the desired target.

Code Implementation

class Solution:
    def nthUglyNumber(self, nth_ugly_target: int) -> int:
        ugly_sequence = [1]
        pointer_for_two = 0
        pointer_for_three = 0
        pointer_for_five = 0

        while len(ugly_sequence) < nth_ugly_target:
            next_val_two = ugly_sequence[pointer_for_two] * 2
            next_val_three = ugly_sequence[pointer_for_three] * 3
            next_val_five = ugly_sequence[pointer_for_five] * 5

            # Selecting the absolute minimum ensures the sequence remains strictly sorted.
            next_ugly_number = min(next_val_two, next_val_three, next_val_five)
            ugly_sequence.append(next_ugly_number)

            # Advancing pointers ensures each multiplier contributes to future unique candidates.
            if next_ugly_number == next_val_two:
                pointer_for_two += 1

            if next_ugly_number == next_val_three:
                pointer_for_three += 1

            # Independent checks allow duplicate values to be skipped via simultaneous advancement.
            if next_ugly_number == next_val_five:
                pointer_for_five += 1

        return ugly_sequence[-1]

Big(O) Analysis

Time Complexity
O(n) – The algorithm uses a single loop that runs exactly n times to generate each successive ugly number in order from smallest to largest. Inside this loop, we perform a constant number of operations: comparing three multiplication candidates, picking the minimum, and advancing pointers. The total operations scale directly in proportion to the target input n, resulting in n linear steps. Thus, the overall time complexity simplifies to O(n).
Space Complexity
O(n) – To build the sequence of ugly numbers in order, we allocate an auxiliary array of size n to store the growing list of generated results. Additionally, we use a few primitive integer variables to act as the three tracking markers for the multipliers and the current sequence index. Because the dynamic array directly scales to hold all n elements, the total extra memory grows linearly with the input size n. Therefore, the auxiliary space complexity simplifies to Big O of n.

Edge Cases

Minimum input where n equals 1
How to Handle:
The algorithm should immediately initialize and return 1 as the first ugly number without entering the loop.
Maximum valid input constraints such as n equals 1690
How to Handle:
A dynamic programming approach with three pointers scales efficiently to O(n) time complexity to compute the result.
Integer overflow during multiplication by 2, 3, or 5
How to Handle:
Using 64-bit integers (long in Java/C++ or standard integers in Python) prevents arithmetic overflow during calculations.
Duplicate values generated by multiple prime multipliers simultaneously
How to Handle:
Using independent conditional checks for the pointers rather than else-if branches ensures duplicate products are skipped.
Zero or negative inputs for n
How to Handle:
Problem constraints specify n is a positive integer, so these can be assumed invalid or handled by returning an error.
0/25 completed