Tuesday, January 24, 2017

Leetcode/各大家 -- 269. Alien Dictionary(BFS)

269. Alien Dictionary(BFS)
Hard
https://leetcode.com/problems/alien-dictionary/
There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list of words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the order of letters in this language.
For example,
Given the following words in dictionary,
[
  "wrt",
  "wrf",
  "er",
  "ett",
  "rftt"
]
The correct order is: "wertf".
Note:
  1. You may assume all letters are in lowercase.
  2. If the order is invalid, return an empty string.
  3. There may be multiple valid order of letters, return any one of them is fine.

思路: use map1: map to store <c, set of char after c>
           use map2: degree to store <c, # of char before c> //based on loop not the final one
           Iterate each two adjacent string, to fill map and update degree 
           use a queue to do BFS. add c to queue when its degree is 0. When remove a c, minus degree
           ! watch edge case,  loop case
Complexity: time: O(n) space: O(n

public class Solution {
    public String alienOrder(String[] words) {
        HashMap<Character, Set<Character>> map = new HashMap<Character, Set<Character>>();//<c, char after c>
        HashMap<Character, Integer> degree = new HashMap<Character, Integer>();//<c, # of char before c>
        StringBuilder res = new StringBuilder();
        //initialize degree map
        for(int i = 0; i < words.length; i++){
            char[] word = words[i].toCharArray();
            for(int j = 0; j < word.length; j++){
                degree.put(word[j], 0);
            }
        }
        //compare adjacent string & fill map
        for(int i = 0; i < words.length - 1; i++){
            String cur = words[i];
            String next = words[i + 1];
            int len = Math.min(cur.length(), next.length());
            for(int j = 0; j < len; j++){
                char c1 = cur.charAt(j);
                char c2 = next.charAt(j);
                if(c1 != c2){
                    Set<Character> set = new HashSet<Character>();//watch 'Set' declaration
                    if(map.containsKey(c1))set = map.get(c1);
                    if(!set.contains(c2)){
                        set.add(c2);
                        map.put(c1, set);
                        degree.put(c2, degree.get(c2) + 1);
                    }
                    break;//rest comparision is meaningless & not record it!
                }else{
                    //edge case - no order: ["wrtkj","wrt"] 1:next stop at end 2: cur still have lefts
                    if(j + 1 == next.length() && j + 1 < cur.length())
                        return "";
                }
            }
        }
        //BFS - use Queue to pop char in order
        Queue<Character> queue = new LinkedList<Character>();
        for(char c: degree.keySet()){
            if(degree.get(c)==0){
                queue.add(c);//eg:[zx,zy], c: z,x
            } 
        }
        while(!queue.isEmpty()){
            char cur = queue.remove();
            res.append(cur);
            if(map.containsKey(cur)){
                for(char c: map.get(cur)){
                    degree.put(c, degree.get(c) - 1);
                    if(degree.get(c) == 0)queue.add(c);//add next char
                }
            }
        }
        //avoid loops. only < possible -- eg: ["qd","ab"] res = qa
        if(res.length() != degree.size())return "";
        return res.toString();
    }
}

ex:   ["wrt","wrf","er","ett","rftt","a","t"] answer: weratf
                                   ?"f"why working
w0(degree) letter before
f1(t)
e1(w)
t1(r)2(a)
r1(e)
a1(r)


Leetcpde -- 263.264 Ugly Number(Recur) + II(DP)

263.264 Ugly Number + II
easy/medium
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, and n does not exceed 1690.

263 I. only need to decide if ugly number, return true/false.
思路: keep mod and divide 2,3,5 till base case.
public class Solution {
    public boolean isUgly(int num) {
        if(num <= 0) return false;
        if(num == 1) return true;
        if(num%2 == 0){
            return isUgly(num/2);
        }
        if(num%3 == 0){
            return isUgly(num/3);
        }
        if(num%5 == 0){
            return isUgly(num/5);
        }
        return false;
    }
}

264 II.
思路1: use dp[n] to track next ugly number
public class Solution {
    public int nthUglyNumber(int n) {
        int i1 = 0, i2 = 0, i3 = 0;
        int num1 = 2,num2 = 3,num3 = 5;//ugly number: 1,2,3,5,
        int[] dp = new int[n];
        dp[0] = 1;
        for(int i = 1; i < n; i++){
            dp[i] = Math.min(num1, Math.min(num2, num3));
            if(dp[i] == num1){
                i1++;
                num1 = 2*dp[i1];
            }
            if(dp[i] == num2){
                i2++;
                num2 = 3*dp[i2];
            }
            if(dp[i] == num3){
                i3++;
                num3 = 5*dp[i3];
            }
        }
        return dp[n-1];
    }
}

思路2: use heap to return the min, keep adding min*2, min*3, min*5 and minus n, till n == 0
slow
ublic class Solution {
    public int nthUglyNumber(int n) {
        PriorityQueue<Long> heap = new PriorityQueue<Long>();
        long res = 0;
        heap.add((long)1);
        while(!heap.isEmpty() && n > 0){
            while(res == heap.peek()){
                heap.poll();
                continue;
            }
            res = heap.poll();
            heap.add(res * 2);
            heap.add(res * 3);
            heap.add(res * 5);
            n--;
        }
        return (int)res;
    }
}

Leetcode/Linkedin -- 156. Binary Tree Upside Down (Recur+Itera)

156. Binary Tree Upside Down(Recursion + Iteration)
medium
https://leetcode.com/problems/binary-tree-upside-down/
Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root.
For example:
Given a binary tree {1,2,3,4,5},
    1
   / \
  2   3
 / \
4   5
return the root of the binary tree [4,5,2,#,#,3,1].
   4
  / \
 5   2
    / \
   3   1  

思路1:Recursion, find the leftmost node as the root. Return repoint each new parent - root.left to previous root and root.right;
Complexity: O(N)time, O(N)space stack
public class Solution {
    public TreeNode upsideDownBinaryTree(TreeNode root) {
        if(root == null || root.left == null)return root;
        TreeNode newRoot = upsideDownBinaryTree(root.left);
        //root.left is newRoot everytime
        root.left.left = root.right;
        root.left.right = root;
        root.left = null;
        root.right = null;
        return newRoot;
    }
}

思路2: Iterative, pre is previous root after repoint, use tmp to track the right node of previous root.
Complexity: O(N)time O(1)space

public class Solution {
    public TreeNode upsideDownBinaryTree(TreeNode root) {
        TreeNode cur = root;
        TreeNode pre = null;
        TreeNode tmp = null;
        TreeNode next = null;
        while(cur != null){
            next = cur.left;
            //need tmp to keep the previous right child
            cur.left = tmp;
            tmp = cur.right;
            
            cur.right = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}

Leetcode/各大家 -- 202.258. Happy Number (Math+HashSet), Add Digits(Math)

202. Happy Number (Math + HashSet)
easy
https://leetcode.com/problems/happy-number/
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example: 19 is a happy number
  • 12 + 92 = 82
  • 82 + 22 = 68
  • 62 + 82 = 100
  • 12 + 02 + 02 = 1
Ex: 4, 145 are not happy number
思路: any number after calculation, store it in set. Once encounter any of previous numbers, return false. If n finally goes to 1, return true.

public class Solution {
    public boolean isHappy(int n) {
        HashSet<Integer>set = new HashSet<>();
        while (!set.contains(n)){
            set.add(n);
            n = helper(n);
            if (n == 1)return true;
        }
        return false;
    }
    public int helper(int n){
        int tmp = 0;
        while (n > 0){
            tmp += (n%10)*(n%10);
            n /= 10;
        }
        return tmp;
    }
}

258. Add Digits(Math)
easy
https://leetcode.com/problems/add-digits/
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?

public class Solution {
    public int addDigits(int num) {
        while(num >= 10){
            num = helper(num);
        }
        return num;
    }
    public int helper(int num){
        int tmp = 0;
        while(num > 0){
            tmp += num%10;
            num /= 10;
        }
        return tmp;
    }
}
Follow up O(1)
public int addDigits(int num) {
    return 1 + (num - 1) % 9;
}

Monday, January 23, 2017

Leetcode/各大家 -- 13. Roman to Integer (Math)

13. Roman to Integer (Math, str)
easy
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.

思路: 倒着走array, 如果 cur >= post (eg: XI), res += cur val,
                                   else  cur < post (eg: IX) res -= cur val


public class Solution {
    public int romanToInt(String s) {
        int res = 0;
        int len = s.length();
        HashMap<Character,Integer> map = new HashMap<Character,Integer>();
        map.put('I',1);
        map.put('V',5);
        map.put('X',10);
        map.put('L',50);
        map.put('C',100);
        map.put('D',500);
        map.put('M',1000);
        res = map.get(s.charAt(len - 1));
        for(int i = len - 2; i >= 0; i--){//eg: XI = 11, IX = 9
            int cur = map.get(s.charAt(i));
            int post = map.get(s.charAt(i + 1));
            if(cur >= post){
                res += cur;
            }else{
                res -= cur;
            }
        }
        return res;
    }
}

Sunday, January 22, 2017

Leetcode/F家 -- 209. Minimum Size Subarray Sum(window: two ptr)

209. Minimum Size Subarray Sum(window: two ptr)
Medium
https://leetcode.com/problems/minimum-size-subarray-sum/
相关题: http://rainykat.blogspot.com/2017/01/leetcode-76-minimum-window-substring.html
Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.
For example, given the array [2,3,1,2,4,3] and s = 7,
the subarray [4,3] has the minimal length under the problem constraint.
More practice:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).

思路: 2 pointers. i is the start of subarray, j is end, keep tracking min of len = j-i +1;
          Outerloop: j<nums.length Since keep a window [i,j] subarray end at j,
          Innerloop: while(sum>=s) keep subtracting i, update len is min


public int minSubArrayLen(int s, int[] nums) {
        int len = nums.length + 1;//any max value to be overwrite
        int i = 0, j = 0;
        int sum = 0;
        while(j < nums.length){//find min subarray[i,j]
            sum += nums[j];
            while(sum >= s){
                len = Math.min(len, j - i + 1);//i is valid at this point
                sum -= nums[i];
                i++;
            }
            j++;
        }
        return len == nums.length + 1 ? 0:len;
    }