Problem
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
Thoughts
I found this problem very hard and had to look at the solution.
Solution
General Idea
Key Observations:
- The
k
th ugly number is a2
,3
or5
multiple of a previousw
th ugly number wherew
is less thani
. - To find the
w
th ugly number that will lead toi
th ugly number,w
is either the index of a previous ugly number that multiple by2
,3
or5
will give the an ugly number that is just abovei-1
th ugly number
Algorithm:
- To find the
w
th ugly number that would lead to thek
th ugly number, we will keep a three indexes:i
: the smallest index such that wheni
th ugly number multiply by2
, the number is more thani-1
th ugly numberj
: same asi
but for3
k
: same asi
but for5
- Advance
i
,j
,k
by1
every time we compute a new ugly number
Implementation