Problem Description
Given an integer n, the task is to find the nth ugly number. An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. For example, for n = 10, the sequence of ugly numbers is [1, 2, 3, 4, 5, 6, 8, 9, 10, 12], so the 10th ugly number is 12.
Key Insights
- Ugly numbers are generated by multiplying smaller ugly numbers by 2, 3, or 5.
- Use dynamic programming to build a sequence of ugly numbers starting from 1.
- Maintain three pointers (for factors 2, 3, and 5) that determine the next candidate ugly number.
- Avoid duplicate entries by checking and advancing all pointers that match the current minimum candidate.
- The approach runs in O(n) time and uses O(n) space.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(n)
Solution
The solution uses a dynamic programming approach. We maintain an array (or list) that stores the ugly numbers in ascending order, starting with 1. Three pointers are used—each corresponding to the multipliers 2, 3, and 5. For each iteration:
- Calculate the next possible ugly numbers by multiplying the number pointed to by each pointer with 2, 3, and 5.
- Select the minimum of these candidates as the next ugly number.
- Increment the corresponding pointer(s) to avoid duplicate calculations.
- Continue until the nth ugly number is generated. This process ensures that each ugly number is generated in order and without duplicates.