LeetCode 263 + 264 Ugly Number I II


Related: LeetCode 313 - Super Ugly Number
LIKE CODING: LeetCode [264] 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. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
Note that 1 is typically treated as an ugly number.
  1. The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones.
  2. An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number.
  3. The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3.
  4. Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).
    int nthUglyNumber(int n) {
        if(n<1) return 0;
        deque<double> vec2, vec3, vec5;
        vec2.push_back(1);
        for(int i=0; i<n; ++i){
           double v2 = vec2.empty()?LLONG_MAX:vec2.front();
           double v3 = vec3.empty()?LLONG_MAX:vec3.front();
           double v5 = vec5.empty()?LLONG_MAX:vec5.front();
           double v = min(v2, min(v3, v5));
           if(i==n-1) return v;
           if(v==v2){
               vec2.pop_front();
               vec2.push_back(v*2);
               vec3.push_back(v*3);
               vec5.push_back(v*5);
           }else if(v==v3){
               vec3.pop_front();
               vec3.push_back(v*3);
               vec5.push_back(v*5);              
           }else{
               vec5.pop_front();
               vec5.push_back(v*5);
           }
        }
    }
https://leetcode.com/discuss/52716/o-n-java-solution
The ugly-number sequence is 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, … because every number can only be divided by 2, 3, 5, one way to look at the sequence is to split the sequence to three groups as below:
(1) 1×2, 2×2, 3×2, 4×2, 5×2, …
(2) 1×3, 2×3, 3×3, 4×3, 5×3, …
(3) 1×5, 2×5, 3×5, 4×5, 5×5, …
We can find that every subsequence is the ugly-sequence itself (1, 2, 3, 4, 5, …) multiply 2, 3, 5.
Then we use similar merge method as merge sort, to get every ugly number from the three subsequence.
Every step we choose the smallest one, and move one step after,including nums with same value.
public int nthUglyNumber(int n) { int[] ugly = new int[n]; ugly[0] = 1; int index2 = 0, index3 = 0, index5 = 0; int factor2 = 2, factor3 = 3, factor5 = 5; for(int i=1;i<n;i++){ int min = Math.min(Math.min(factor2,factor3),factor5); ugly[i] = min; if(factor2 == min) factor2 = 2*ugly[++index2]; if(factor3 == min) factor3 = 3*ugly[++index3]; if(factor5 == min) factor5 = 5*ugly[++index5]; } return ugly[n-1]; }
https://discuss.leetcode.com/topic/22982/java-easy-understand-o-n-solution
 public int nthUglyNumber(int n) {
  if(n<=0) return 0;
  int a=0,b=0,c=0;
  List<Integer> table = new ArrayList<Integer>();
  table.add(1);
  while(table.size()<n)
  {
   int next_val = Math.min(table.get(a)*2,Math.min(table.get(b)*3,table.get(c)*5));
   table.add(next_val);
   if(table.get(a)*2==next_val) a++;
   if(table.get(b)*3==next_val) b++;
   if(table.get(c)*5==next_val) c++;
  }
  return table.get(table.size()-1);
 }
http://www.neozone.me/leetcode264.html
This can be easily expanded if there are multiple primes.
    public int nthUglyNumber(int n) {
        int[] uglyNumber = new int[n];
        int[] index = new int[3]; // respectively for 2,3,5
        int[] factor = {2, 3, 5}; // respectively for 2,3,5
        uglyNumber[0] = 1;
        for(int i = 1; i < n; i++){
            int min = Math.min(Math.min(factor[0], factor[1]), factor[2]);
            uglyNumber[i] = min;
            if(min == factor[0]) factor[0] = 2 * uglyNumber[++index[0]];
            if(min == factor[1]) factor[1] = 3 * uglyNumber[++index[1]];
            if(min == factor[2]) factor[2] = 5 * uglyNumber[++index[2]];           
        }
        return uglyNumber[n - 1];
    }
https://leetcode.com/discuss/55304/java-easy-understand-o-n-solution
Compared with previous solution, this one computes each factor twice.
public class Solution { public int nthUglyNumber(int n) { if(n<=0) return 0; int a=0,b=0,c=0; List<Integer> table = new ArrayList<Integer>(); table.add(1); while(table.size()<n) { int next_val = Math.min(table.get(a)*2,Math.min(table.get(b)*3,table.get(c)*5)); table.add(next_val); if(table.get(a)*2==next_val) a++; if(table.get(b)*3==next_val) b++; if(table.get(c)*5==next_val) c++; } return table.get(table.size()-1); } }
https://leetcode.com/discuss/67392/my-java-o-n-implementation-and-explaination
public int nthUglyNumber(int n) { List<Integer> results = new ArrayList<>(); results.add(1); int idx2 = 0; int idx3 = 0; int idx5 = 0; int totalNums= 1; while(totalNums < n ){ int val2 = results.get(idx2) * 2; int val3 = results.get(idx3) * 3; int val5 = results.get(idx5) * 5; int thisPick; if(val2 <= val3 && val2 <= val5){ thisPick = val2; idx2++; } else if(val3 <= val2 && val3 <= val5){ thisPick = val3; idx3++; } else { // (val5 <= val2 && val5 <= val3) thisPick = val5; idx5++; } if(results.get(totalNums-1) != thisPick) { // is possible results.get(totalNums-1) == thisPick?
results.add(thisPick); totalNums++; } } return results.get(n - 1); }
http://shibaili.blogspot.com/2015/08/day-121-264-ugly-number-ii.html
    int nthUglyNumber(int n) {
        vector<int> ugly(n);
        ugly[0] = 1;
        int p2 = 0, p3 = 0, p5 = 0;
         
        for (int i = 1; i < n; i++) {
            int nextUgly = min(ugly[p2] * 2,min(ugly[p3] * 3,ugly[p5] * 5));
             
            if (nextUgly == ugly[p2] * 2) {
                p2++;
            }
            if (nextUgly == ugly[p3] * 3) {
                p3++;
            }
            if (nextUgly == ugly[p5] * 5) {
                p5++;
            }
            ugly[i] = nextUgly;
        }
         
        return ugly[n - 1];
    }
Space Optimization:
Using 3 Queues:
https://leetcode.com/discuss/52710/java-solution-with-three-queues
public int nthUglyNumber(int n) { if (n < 1) return 0; Queue<Long> queue2 = new LinkedList<>(); Queue<Long> queue3 = new LinkedList<>(); Queue<Long> queue5 = new LinkedList<>(); queue2.add(1l); long val = 0; for (int i = 0; i < n; i++) { long v2 = queue2.isEmpty() ? Long.MAX_VALUE : queue2.peek(); long v3 = queue3.isEmpty() ? Long.MAX_VALUE : queue3.peek(); long v5 = queue5.isEmpty() ? Long.MAX_VALUE : queue5.peek(); val = Math.min(v2, Math.min(v3, v5)); if (val == v2) { queue2.poll(); queue2.add(val*2); queue3.add(val*3); } else if (val == v3) { queue3.poll(); queue3.add(val*3); } else queue5.poll(); queue5.add(val*5); } return (int)val; }
X. TreeSet
I think to use TreeSet other than PriorityQueue is easier as you don't need to worry about duplicates. Time complexity is same.

    public int nthUglyNumber(int n) {
        TreeSet<Long> ans = new TreeSet<>();
        ans.add(1L);
        for (int i = 0; i < n - 1; ++i) {
            long first = ans.pollFirst();
            ans.add(first * 2);
            ans.add(first * 3);
            ans.add(first * 5);
        }
        return ans.first().intValue();
    }

X. PriorityQueue
https://discuss.leetcode.com/topic/25088/java-solution-using-priorityqueue
Different way, but not efficient.
public int nthUglyNumber(int n) { if(n==1) return 1; PriorityQueue<Long> q = new PriorityQueue(); q.add(1l); for(long i=1; i<n; i++) { long tmp = q.poll(); while(!q.isEmpty() && q.peek()==tmp) tmp = q.poll(); q.add(tmp*2); q.add(tmp*3); q.add(tmp*5); } return q.poll().intValue(); }
Different https://leetcode.com/discuss/53615/java-solution-with-one-min-heap
http://fisherlei.blogspot.com/2015/10/leetcode-ugly-number-ii-solution.html
7:    int nthUglyNumberGeneral(int n, vector<int>& factors) {  
8:      vector<int> uglys(1,1);  
9:      vector<int> indexes(factors.size(), 0);  
10:      while(uglys.size() < n) {  
11:        int min_v = INT_MAX;  
12:        int min_index = 0;  
13:        for(int k =0; k< factors.size(); k++) {  
14:          int temp = uglys[indexes[k]] * factors[k];  
15:          if(temp < min_v) {  
16:            min_v = temp;  
17:            min_index = k;  
18:          }  
19:        }  
20:        indexes[min_index]++;  
21:        // need to avoid duplicate ugly number  
22:        if(uglys[uglys.size()-1] != min_v) {  
23:          uglys.push_back(min_v);  
24:         }  
25:      }  
26:      return uglys[n-1];  
27:    } 
从空间的优化来说,没有必要用一个uglys的数组保存所有的ugly number,尤其是当n是个非常大的数字。对于indexes指针扫过的ugly number,都可以丢掉了
https://leetcode.com/discuss/53009/interesting-bounds-about-this-problem
  1. Actually, the input space is much smaller than expected if we insist an int range output. When input n is greater than 1691, the output overflows the int range.
  2. Another way to view this bound is that all ugly numbers must be in the form 2^a*3^b*5^c. Since we have log2(Integer.MAX_VALUE)=a<31log3(Integer.MAX_VALUE)=b<20 andlog5(Integer.MAX_VALUE)=c<14, the combination allowed is surely under31*20*14~=8400.
LeetCode [263] Ugly Number
Write a program to check whether a given number is an ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.
    bool isUgly(int num) {
        if(num==0) return false;
        if(num==1) return true;
        for(int i=2; i<6; ++i){
            while(num%i==0) num /=i;   
        }
        return num==1;
    }
http://shibaili.blogspot.com/2015/08/day-121-264-ugly-number-ii.html
    bool isUgly(int num) {
        if (num == 1) return true;
        while (true) {
            int t = num;
            if (num % 2 == 0) {
                num /= 2;
            }
            if (num % 3 == 0) {
                num /= 3;
            }
            if (num % 5 == 0) {
                num /= 5;
            }
            if (num == t) return false;
            if (num == 1) return true;
        }
    }

http://www.cnblogs.com/grandyang/p/4741934.html
    bool isUgly(int num) {
        while (num >= 2) {
            if (num % 2 == 0) num /= 2;
            else if (num % 3 == 0) num /= 3;
            else if (num % 5 == 0) num /= 5;
            else return false;
        }
        return num == 1;
    }

    bool isUgly(int num) {
        if (num <= 0) return false;
        while (num % 2 == 0) num /= 2;
        while (num % 3 == 0) num /= 3;
        while (num % 5 == 0) num /= 5;
        return num == 1;
    }
https://leetcode.com/discuss/57435/simple-java-solution-for-ugly-number-problem
public boolean isUgly(int num) { if (num == 0) return false; if (num == 1) return true; while (num % 5 == 0) num /= 5; while (num % 3 == 0) num /= 3; while (num % 2 == 0) num /= 2; return num == 1; }


https://github.com/careercup/CtCI-6th-Edition/tree/master/Java/Ch%2017.%20Hard/Q17_09_Kth_Multiple
Design an algorithm to find the kth number such that the only prime factors are 3, 5, and 7. Note that 3, 5, and 7 do not have to be factors, but it should bot have any other prime factors. For example, the first several multiples would be (in order) 1, 3, 5, 7, 9, 15, 21

If we separated the list from the beginning by the constant factors, then we'd only need to check the first of
the multiples of 3, 5 and 7. All subsequent elements would be bigger.
public static int getKthMagicNumber(int k) {
if (k < 0) {
return 0;
}
int val = 0;
Queue<Integer> queue3 = new LinkedList<Integer>();
Queue<Integer> queue5 = new LinkedList<Integer>();
Queue<Integer> queue7 = new LinkedList<Integer>();
queue3.add(1);
for (int i = 0; i <= k; i++) { // Include 0th iteration through kth iteration
int v3 = queue3.size() > 0 ? queue3.peek() : Integer.MAX_VALUE; 
int v5 = queue5.size() > 0 ? queue5.peek() : Integer.MAX_VALUE;
int v7 = queue7.size() > 0 ? queue7.peek() : Integer.MAX_VALUE;
val = Math.min(v3, Math.min(v5, v7));
if (val == v3) {
queue3.remove();
queue3.add(3 * val);
queue5.add(5 * val);
} else if (val == v5) {
queue5.remove();
queue5.add(5 * val);
} else if (val == v7) {
queue7.remove();
}
queue7.add(7 * val);
}
return val;
}

public static int removeMin(Queue<Integer> q) {
int min = q.peek();
for (Integer v : q) {
if (min > v) {
min = v;
}
}
while (q.contains(min)) {
q.remove(min);
}
return min;
}

public static void addProducts(Queue<Integer> q, int v) {
q.add(v * 3);
q.add(v * 5);
q.add(v * 7);
}

public static int getKthMagicNumber(int k) {
if (k < 0) {
return 0;
}
int val = 1;
Queue<Integer> q = new LinkedList<Integer>();
addProducts(q, 1);
for (int i = 0; i < k; i++) { // Start at 1 since we've already done one iteration
val = removeMin(q);
addProducts(q, val);
}
return val;
}

Brute Force
public static ArrayList<Integer> allPossibleKFactors(int k) {
ArrayList<Integer> values = new ArrayList<Integer>();
for (int a = 0; a <= k; a++) { // 3
int powA = (int) Math.pow(3,  a);
for (int b = 0; b <= k; b++) { // 5
int powB = (int) Math.pow(5,  b);
for (int c = 0; c <= k; c++) { // 7
int powC = (int) Math.pow(7, c);
int value = powA * powB * powC;
if (value < 0 || powA == Integer.MAX_VALUE || powB == Integer.MAX_VALUE || powC == Integer.MAX_VALUE) {
value = Integer.MAX_VALUE;
}
values.add(value);
}
}
}
return values;
}

public static int getKthMagicNumber(int k) {
ArrayList<Integer> possibilities = allPossibleKFactors(k);
Collections.sort(possibilities);
return possibilities.get(k);
}
Read full article from LIKE CODING: LeetCode [264] Ugly Number II

Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts