Ugly Number II

Write a program to find the n-th ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5

Example:

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.

Note:  

  1. 1 is typically treated as an ugly number.
  2. n does not exceed 1690.
 class Solution {
        public int nthUglyNumber(int n) {
            int[] ugly = new int[n];
            ugly[0] = 1;
            int indexOf2 = 0, indexOf3 = 0, indexOf5 = 0;
            int factorOf2 = 2, factorOf3 = 3, factorOf5 = 5;
            for(int i=1;i<n;i++){
                int min = Math.min(Math.min(factorOf2,factorOf3),factorOf5);
                ugly[i] = min;
                if(factorOf2 == min)
                    factorOf2 = 2*ugly[++indexOf2];
                if(factorOf3 == min)
                    factorOf3 = 3*ugly[++indexOf3];
                if(factorOf5 == min)
                    factorOf5 = 5*ugly[++indexOf5];
            }
            return ugly[n-1];
        }
    }


Here, we are going to solve using efficient solution but having O(n) extra space. Ugly number sequence are 1, 2, 3, 4, 5, 8, 9, 10, 12, 15... A number should be divided only by 2, 3, 5 so that only it can become a ugly number. So for that, a number can be formed by upcoming split sequences (solution can be come up based on Hints given on Leetcode)

1×2, 2×2, 3×2, 4×2, 5×2, …
1×3, 2×3, 3×3, 4×3, 5×3, …
1×5, 2×5, 3×5, 4×5, 5×5, …

Below you find the detailed explanation of working of above code...,

Initially
ugly[] = | 1 | i2 = i3 = i5 = 0; First iteration ugly[1] = Min(ugly[i2]*2, ugly[i3]*3, ugly[i5]*5) = Min(2, 3, 5) = 2 ugly[] = | 1 | 2 | i2 = 1, i3 = i5 = 0 (i2 got incremented ) Second iteration ugly[2] = Min(ugly[i2]*2, ugly[i3]*3, ugly[i5]*5) = Min(4, 3, 5) = 3 ugly[] = | 1 | 2 | 3 | i2 = 1, i3 = 1, i5 = 0 (i3 got incremented ) Third iteration ugly[3] = Min(ugly[i2]*2, ugly[i3]*3, ugly[i5]*5) = Min(4, 6, 5) = 4 ugly[] = | 1 | 2 | 3 | 4 | i2 = 2, i3 = 1, i5 = 0 (i2 got incremented ) Fourth iteration ugly[4] = Min(ugly[i2]*2, ugly[i3]*3, ugly[i5]*5) = Min(6, 6, 5) = 5 ugly[] = | 1 | 2 | 3 | 4 | 5 | i2 = 2, i3 = 1, i5 = 1 (i5 got incremented )
Related Post:

Click here for April month challenges with solution and explanation

Click Follow button to receive latest updates from us instantly.

Please let us know about your views in comment section.

Help Others, Please Share..!!!!

                                                     😍..Happy Coding...😍

Comments

Popular posts from this blog

First Unique Character in a String

Balanced Binary Tree

Majority Element

Smallest Range II