ProblemPermalink
Problem ID: 264
Title: Ugly Number II
Difficulty: Medium
Description:
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
ThoughtsPermalink
I found this problem very hard and had to look at the solution.
SolutionPermalink
General Idea
Key Observations:
- The
kth ugly number is a2,3or5multiple of a previouswth ugly number wherewis less thani. - To find the
wth ugly number that will lead toith ugly number,wis either the index of a previous ugly number that multiple by2,3or5will give the an ugly number that is just abovei-1th ugly number
Algorithm:
- To find the
wth ugly number that would lead to thekth ugly number, we will keep a three indexes:i: the smallest index such that whenith ugly number multiply by2, the number is more thani-1th ugly numberj: same asibut for3k: same asibut for5
- Advance
i,j,kby1every time we compute a new ugly number
ImplementationPermalink