Tuesday, January 3, 2017

Leetcode/各大家--161. One Edit Distance(substring)

161. One Edit Distance(substring)
  • Difficulty: Medium
https://leetcode.com/problems/one-edit-distance/


Given two strings S and T, determine if they are both one edit distance apart.

Company:



思路:一共有3种情况满足1edit distance
         case1:len1 = len2, "abc" vs "adc"//replace one char from str1 
                    1: check if diff > 1
         case2: len1 - len2 = 1,"abc" vs "ac" //delete one char from str1
         case3: len2 - len1 = 1, "ab" vs "abc";//delete one char from str2
                   2.3 find the different char, compare the rest of substring

关键字: substring, str.equals(str2);


public class Solution {
    public boolean isOneEditDistance(String s, String t) {
        int count =0;
        int len1 = s.length(), len2 = t.length();
        if(len1 == len2){
            for(int i = 0; i < s.length(); i++){
                if(s.charAt(i) != t.charAt(i)) count++;
                if(count > 1) return false;
            }
            return !s.equals(t);
        }else if(len1 - len2 == 1||len1 - len2 == -1){
            int i = 0, j = 0;
            while(i < len1 && j < len2){
                if(s.charAt(i) != t.charAt(j)){
                    String tmp1, tmp2;
                    if(len1 < len2){ 
                        tmp1 = s.substring(i, len1);
                        tmp2 = t.substring(j + 1, len2);
                    }else{
                        tmp1 = s.substring(i + 1, len1);
                        tmp2 = t.substring(j, len2);
                    }
                    return tmp1.equals(tmp2);
                }
                i++;
                j++;
            }
            return true;//"a", ""
        }
        return false;
        
    }
}

Monday, January 2, 2017

算法小结--各种算法

Heap (new PriorityQueue<>())
-complete binary tree, 通常会用到comparator来sort specific data class
-parent node val is greater or smaller than  child's value
-Complexity: 
   find min/max: O(1)
   insert: O(lgN) - max height of tree 
   remove(only min/max):O(lgn) - use the last one to put in tree and rearramge
O(1) get
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(10(optional initial capacity), Collections.reverseOrder()); --max 
insert 是O(logK) by height of tree;  最小(default)最大的在上面
 

EX:
» 23. Merge k Sorted Lists (heap or Divide&Conquer) 各大家
http://rainykat.blogspot.com.tr/2017/01/leetcode-23-merge-k-sorted-lists-heap.html
» 451. Sort Characters By Frequency(HashMap + Heap) G家亚麻
http://rainykat.blogspot.com.tr/2017/01/leetcodeg-451-sort-characters-by.html
 

Math
»  202.258. Happy Number (Math+HashSet), Add Digits(Math)各大家
http://rainykat.blogspot.com.tr/2017/01/leetcode-202-happy-number-mathhashset.html 
»  415. Add Strings G家Airbnb
http://rainykat.blogspot.com/2017/01/leetcode-ga-415-add-stringsmath.html 
»  43. Multiply Strings F家Twitter
http://rainykat.blogspot.com/2017/01/leetcodef-43-multiply-stringsmath.html
»  168. Excel Sheet Column Title 各大家
http://rainykat.blogspot.com/2017/01/leetcode-168-excel-sheet-column-title.html 
»  311. Sparse Matrix Multiplication F家LinkedIn
http://rainykat.blogspot.com/2016/12/leetcodeflinkedin-sparse-matrix.html 
»  13. Roman to Integer 各大家
String 倒着读
http://rainykat.blogspot.com.tr/2017/01/leetcode-13-roman-to-integer-math.html 

Array  
EX: 
» 334. Increasing Triplet Subsequence (初始值) F家
initialize min with Integer.MAX_VALUE to be overwritten
http://rainykat.blogspot.com.tr/2017/01/leetcodef-334-increasing-triplet.html
» 238. Product of Array Except Self 各大家
双向遍历法
http://rainykat.blogspot.com/2017/01/leetcode-238-product-of-array-except.html
» 277. Find the celebrity F家,LinkedIn 
2 pass loop array(1 for find candidates, 1 for validate candidates)
http://rainykat.blogspot.com/2017/01/leetcodeflinkedin-277-find.html
» 189. Rotate Array 微软, bloomberg
reverse array 3 parts (0-k-1,k-end,0-end)
http://rainykat.blogspot.com/2017/01/leetcodebloomberg-189-rotate-array.html
» 57. Insert Interval F家G家LinkedIn
http://rainykat.blogspot.com/2017/01/leetcode-57-insert-intervalarray-sort.html
» 387. First Unique Character in a String高频
巧用 int[] arr= new int[26], arr[c-'a'] 字母对应
https://leetcode.com/problems/plus-one/#/description 
» 66. Plus One 高频
思路: - add 1 from tail, track increment by inc
           - once inc = 0, return. Else in the pattern of 100...., 巧用inc
https://leetcode.com/problems/plus-one/#/description


String
常用代码
1.考虑substring str = s.substring(i,len) //str[i,len)
    - s.substring(i, i+len)//get substring of length = len starting from i
2. char to int: int a = charA-'0';
    int to char: char a = (char) b;
    int to string: Integer.toString(a);
    String to Int: int foo = Integer.parseInt("1234");
3. str.trim();//remove extra space in the start & end of string (LC151)
4. sb.setCharAt(index,c)//string builder to replace char
5. str.split("//s+") or  str.split(" +")//in split, regular expression

EX:
» 273. Integer to English Words F家微软
tricky, string with recursion and math sense
http://rainykat.blogspot.com/2017/01/leetcodef-273-integer-to-english-words.html 
» 434. Number of Segments in a String
watch the words start with ' '
http://rainykat.blogspot.com.tr/2017/01/leetcode-434-number-of-segments-in.html 
» 67. Add Binary F家
char to num convert: int a = charA - '0';
http://rainykat.blogspot.com/2016/12/leetcodef-add-binary.html  
» 161. One Edit Distance 各大家
用substring 来check是否剩余的string相同 
http://rainykat.blogspot.com/2017/01/leetcode-161-one-edit-distancesubstring.html 
» 5. Longest Palindromic Substring 
保持且只查大于当前长度的substring
http://rainykat.blogspot.com/2017/04/leetcode-5-longest-palindromic.html 


 
Stack--Deque (new LinkedList<>())
» 20. Valid Parentheses 各大家 巧用stack来存starting part of 括号, check括号是否match closing part
http://rainykat.blogspot.com/2017/01/leetcode-20-valid-parentheses.html
» 71. Simplify Path 微软,脸家
http://rainykat.blogspot.com/2017/01/leetcodef-71-simplify-pathstack.html 
» 66. Basic Calculator II 高频
http://rainykat.blogspot.com/2017/04/leetcode-227-basic-calculator-ii-stack.html

 Window 

1. fix length window
2. put one in, remove one out
» 567. Permutation in String

Leetcode/F家,LinkedIn--277. Find the Celebrity(Array)

277. Find the Celebrity(Array)
  • Difficulty: Medium
https://leetcode.com/problems/find-the-celebrity/


Suppose you are at a party with n people (labeled from 0 to n - 1) and among them, there may exist one celebrity. The definition of a celebrity is that all the other n - 1 people know him/her but he/she does not know any of them.
Now you want to find out who the celebrity is or verify that there is not one. The only thing you are allowed to do is to ask questions like: "Hi, A. Do you know B?" to get information of whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense).
You are given a helper function bool knows(a, b) which tells you whether A knows B. Implement a function int findCelebrity(n), your function should minimize the number of calls to knows.
Note: There will be exactly one celebrity if he/she is in the party. Return the celebrity's label if there is a celebrity in the party. If there is no celebrity, return -1.

思路: loop 2次array.  The first pass is to pick out the candidate. If candidate knows i, then switch candidate. (the candidates know nobody)
The second pass is to check whether the candidate is real.(if all other people know the candidate and candidate not know all other people)
关键字:array
/* The knows API is defined in the parent class Relation.
      boolean knows(int a, int b); */

public class Solution extends Relation {
    public int findCelebrity(int n) {
        int candidate = 0;
        //1 pass: find the celebrity - find the person that knows nobody after him(watch互不知道的情况0,返回-1);
        for(int i = 1; i < n; i++){
           if(knows(candidate, i))candidate = i;
        }
        //2 pass: check celebrity real - check if he knows nobody & eveyone knows him
        for(int i = 0; i < n; i++){
            if(i != candidate){
                if(knows(candidate, i)||!knows(i,candidate))return -1;
            }
        }
        return candidate;
    }
}

Leetcode/F家--88. Merge Sorted Array(Merge Sort)

88. Merge Sorted Array(Merge Sort)
  • Difficulty: Easy
https://leetcode.com/problems/merge-sorted-array/
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.

Company: Microsoft Bloomberg Facebook

思路:就是MergeSort的Merge part,建一个tmp array把nums[1]的elements copy过去,
           compare tmp[i] vs nums2[j], store the smaller one in nums[1]
关键字:Merge Sort

public class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int[] tmp= new int [m];
        for(int i = 0;i < m;i++){
            tmp[i]=nums1[i];
        }
        int i=0,j=0,k=0;
        while (i<m && j<n){
            if(tmp[i]<nums2[j]){
                nums1[k]=tmp[i];
                i++;
            }else{
                nums1[k]=nums2[j];
                j++;
            }
            k++;
        }
        while (i<m) nums1[k++]=tmp[i++];
        while (j<n) nums1[k++]=nums2[j++];
    }
}

Full Merge sort
https://www.hackerrank.com/contests/hw1/challenges/merge-sort/copy-from/8324041
Sort function:
public void sort(int left, int right, int[] arr){
           if(left<right){
                      int mid = left + (right-left)/2;
                      sort(left,mid);
                      sort(mid+1,right);
                      merge(left,mid,right,arr);
          }
}




Sunday, January 1, 2017

Leetcode/Bloomberg -- 122. Best Time to Buy and Sell Stock II(Greedy)


122. Best Time to Buy and Sell Stock II(Greedy)
  • Difficulty: Medium
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

思路:每一步涨的都加入结果,则会得到最大的收益。
关键字: Greedy

 
public class Solution {
    public int maxProfit(int[] prices) {
        /* greedy: get profit every increase, then you can get the total max profit;*/
        int res = 0;
        for(int i=1;i<prices.length;i++){
            if(prices[i]-prices[i-1]>0) res+=prices[i]-prices[i-1];//increase
        }
        return res;
    }
}

Leetcode/各大家 -- 121. Best Time to Buy and Sell Stock

121. Best Time to Buy and Sell Stock
  • Difficulty: Easy
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1]
Output: 0

In this case, no transaction is done, i.e. max profit = 0.

Company: Amazon Microsoft Bloomberg Uber Facebook

解法:用Kanede's algorithm, compute max_ending_here if earn money add previous index + pirce[i]-prices[i-1]>0else0, track the overall max_so_far
相关题:http://rainykat.blogspot.com/2016/12/leetcodelinkedin-maximum-subarraydp-or.html
思路:DP, Kanede's algorithm(for max subarray)

public class Solution {
    public int maxProfit(int[] prices) {
        int n = prices.length;
        int max_so_far = 0,max_ending_here =0;//max sum of arr[0..i]
        for(int i = 1; i < n; i++){
           max_ending_here = Math.max(0,max_ending_here + prices[i]-prices[i-1]);
            max_so_far = Math.max(max_so_far,max_ending_here);
        }
        return max_so_far;
    }
}



Leetcode/F家--38.Count and Say(DP)

38. Count and Say
  • Difficulty: Easy

https://leetcode.com/problems/count-and-say/

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string

思路: DP问题,举例发现i+1的string就是根据i的string来count & say。
         3: 21 就是根据(2:11) 数,有2个1。
         建个for loop从1加到n,每个数都call helper func, helper来track下一个不同的char,建sb
Complexity: Time O(MN) -  helper run Str len from: 1,2,  4...
                   Space O(N) -  make copy of entire string
 
关键字:DP ,StingBuilder -- 可直接append int(也可以写成 String.valueOf(int)) & char

public class Solution {
    public String countAndSay(int n) {
        String res = "1";
        for(int i=1;i<n;i++){
            res = helper(res);
        }
        return res;
    }
    
    public String helper(String res){
        StringBuilder sb = new StringBuilder();
        char last = res.charAt(0);
        int count = 1;
        for(int i = 1;i<res.length();i++){
            if(res.charAt(i) == last){
                count++;
            }else{
                sb.append(count);
                sb.append(last);
                last = res.charAt(i);
                count = 1;
            }
        }
        sb.append(count);
        sb.append(last);
        return sb.toString();
    }
}