Tuesday, July 21, 2015

Intersection of Two LinkedList -- Leetcode

Question:
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3
begin to intersect at node c1.
Notes:
  • If the two linked lists have no intersection at all, return null.
  • The linked lists must retain their original structure after the function returns.
  • You may assume there are no cycles anywhere in the entire linked structure.
  • Your code should preferably run in O(n) time and use only O(1) memory.
Answer:
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
         if(!headA || !headB)return NULL;
       
         ListNode *pA = headA, *pB = headB;
         int num1=0, num2=0;
         while(pA){
             pA = pA->next;
             num1++;
         }
         while(pB){
             pB = pB->next;
             num2++;
         }
       
         pA = headA;
         pB = headB;
         if(num1 >= num2){
             int extra = num1-num2;
             while(extra-- > 0){
                 pA = pA->next;
             }
         }else if(num1 < num2){
             int extra = num2-num1;
             while(extra-- > 0){
                 pB = pB->next;
             }
         }
       
         while(pA && pB && pA!=pB){
                 pA = pA->next;
                 pB = pB->next;
         }
         if(pA && pB){
            return pA;
         }else{
            return NULL;
         }
    }
};

Wednesday, July 15, 2015

Word Search II (Boggle Game) -- Leetcode

Question:
Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
For example,
Given words = ["oath","pea","eat","rain"] and board =
[
  ['o','a','a','n'],
  ['e','t','a','e'],
  ['i','h','k','r'],
  ['i','f','l','v']
]
Return ["eat","oath"].
Note:
You may assume that all inputs are consist of lowercase letters a-z.
You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier?
If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first.

Answer:
public class Solution {

    public List<String> findWords(char[][] board, String[] words) {
        List<String> res = new ArrayList<String>();
        //to avoid duplicate
        Set<String> sset = new HashSet<String>();
        String tmp = new String("");
        int m = board.length;
        int n = board[0].length;
        
        Trie trie = new Trie();
        for(int i=0; i< words.length; ++i){
            trie.insert(words[i]);
        }
        boolean[][] visited = new boolean[m][n];
        for(int i=0;i<m;++i){
            for(int j=0;j<n;++j){
                visited[i][j] = false;
            }
        }
        
        for(int i=0; i<m; ++i){
            for(int j=0; j<n; ++j){
               DFS(board, i, j, visited, tmp, trie, sset); 
            }
        }
        for(String s : sset){
            res.add(s);
        }
        return res;
    }
    
    public void DFS(char[][] board, int i, int j, boolean[][] visited, String str, Trie trie, Set<String> sset){
        str = str += board[i][j];
        
        if(!trie.startsWith(str)){
        str = str.substring(0,str.length()-1);
            return;
        }
        
        if(trie.search(str)){
            sset.add(str);
        }
        visited[i][j] = true;
        
        int m = board.length;
        int n = board[0].length;
        if(j-1 >= 0 && !visited[i][j-1]){
            DFS(board, i, j-1, visited, str, trie, sset);
        }
        if(j+1 < n && !visited[i][j+1]){
            DFS(board, i, j+1, visited, str, trie, sset);
        }
        if(i-1 >= 0 && !visited[i-1][j]){
            DFS(board, i-1, j, visited, str, trie, sset);
        }
        if(i+1 < m && !visited[i+1][j]){
            DFS(board, i+1, j, visited, str, trie, sset);
        }
        
        //backtrack, important!
        visited[i][j] = false;
        str = str.substring(0,str.length()-1);
        return;
    }
    
    
//Trie tree    
  class TrieNode {
    // Initialize your data structure here.
    public char c;
    // important!
    public boolean isEnd;
    public int count;
    public ArrayList<TrieNode> children;
    
    public TrieNode(char cha) {
        this.c = cha;
        isEnd = false;
        count = 1;
        children = new ArrayList<TrieNode>();
    }
    //return the node in the chilren == cha
    public TrieNode rtnchildNode(char cha){
        for(TrieNode child : this.children){
            if(child.c == cha){
                return child;
            }
        }
        return null;
    }
  }

  class Trie {
    private TrieNode root;

    public Trie() {
        root = new TrieNode(' ');
    }

    // Inserts a word into the trie.
    public void insert(String word) {
        TrieNode cur = root;
        TrieNode next = null;
        
        for(int i=0;i< word.length(); ++i){
            next = cur.rtnchildNode(word.charAt(i));
            
            if(next!=null){
                next.count++;
                cur=next;
                
            }else{
                TrieNode insertNewNode = new TrieNode(word.charAt(i));
                cur.children.add(insertNewNode);
                cur=insertNewNode;
            }
            if(i== word.length()-1){
                cur.isEnd = true;
            }
        }
    }

    // Returns if the word is in the trie.
    public boolean search(String word) {
        TrieNode cur = root;
        TrieNode next = null;
        
        for(int i=0; i< word.length(); ++i){
            next = cur.rtnchildNode(word.charAt(i));
            if(next != null){
                cur = next;
            }else{
                return false;
            }
            //important!Judge the tail char whether 'isEnd'
            if(i == word.length()-1){
                if(cur.isEnd == true){
                    return true;
                }
            }
        }
        return false;
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
        TrieNode cur = root;
        TrieNode next = null;
        
        for(int i=0; i< prefix.length(); ++i){
            next = cur.rtnchildNode(prefix.charAt(i));
            
            if(next != null){
                cur = next;
            }else{
                return false;
            }
        }
        return true;
    }
  }
}

Tuesday, July 14, 2015

Trie (Prefix) Tree -- Leetcode

Question:
Implement a trie with insert, search, and startsWith methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z.
Answer:
class TrieNode {
    // Initialize your data structure here.
    public char c;
    //important!
    public boolean isEnd;
    public int count;
    public ArrayList<TrieNode> children;
    
    public TrieNode(char cha) {
        this.c = cha;
        isEnd = false;
        count = 1;
        children = new ArrayList<TrieNode>();
    }
    //return the child node whose char == cha
    public TrieNode rtnchildNode(char cha){
        for(TrieNode child : this.children){
            if(child.c == cha){
                return child;
            }
        }
        return null;
    }
}

public class Trie {
    private TrieNode root;

    public Trie() {
        root = new TrieNode(' ');
    }

    // Inserts a word into the trie.
    public void insert(String word) {
        TrieNode cur = root;
        TrieNode next = null;
        
        for(int i=0;i< word.length(); ++i){
            next = cur.rtnchildNode(word.charAt(i));
            
            if(next!=null){
                next.count++;
                cur=next;
                
            }else{
                TrieNode insertNewNode = new TrieNode(word.charAt(i));
                cur.children.add(insertNewNode);
                cur=insertNewNode;
            }
            if(i== word.length()-1){
                cur.isEnd = true;
            }
        }
    }

    // Returns if the word is in the trie.
    public boolean search(String word) {
        TrieNode cur = root;
        TrieNode next = null;
        
        for(int i=0; i< word.length(); ++i){
            next = cur.rtnchildNode(word.charAt(i));
            if(next != null){
                cur = next;
            }else{
                return false;
            }
            //important!Judge the tail char whether 'isEnd'
            if(i == word.length()-1){
                if(cur.isEnd == true){
                    return true;
                }
            }
        }
        return false;
    }

    // Returns if there is any word in the trie that starts with the given prefix.
    public boolean startsWith(String prefix) {
        TrieNode cur = root;
        TrieNode next = null;
        
        for(int i=0; i< prefix.length(); ++i){
            next = cur.rtnchildNode(prefix.charAt(i));
            
            if(next != null){
                cur = next;
            }else{
                return false;
            }
        }
        return true;
    }
}

// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");

Sunday, July 12, 2015

Number of Islands -- Leetcode

Question:
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
Answer:
class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        int num = 0;
        int m = grid.size();
        if(m==0){
            return 0;
        }
        int n = grid[0].size();
        
        vector<vector<bool>> flag = vector<vector<bool>>(m, vector<bool>(n,false));
        
        for(int i=0;i<m;++i){
            for(int j=0;j<n;++j){
                if(grid[i][j] == '1' && !flag[i][j]){
                    num++;
                    DFS(grid,i,j,flag);
                }
            }
        }
        return num;
    }
    
    void DFS(vector<vector<char>>& grid, int i, int j, vector<vector<bool>>& flag){
        int m = grid.size();
        int n = grid[0].size();
        if(i<0 || i>=m || j<0 || j>=n){
            return;
        }
        //avoid tranverse already visited point.
        if(flag[i][j]){
            return;
        }
        
        if(grid[i][j] == '1'){
            flag[i][j] = true;
            DFS(grid, i+1,j,flag);
            DFS(grid, i-1,j,flag);
            DFS(grid, i,j-1,flag);
            DFS(grid, i,j+1,flag);
        }
        return;
    }
};

Friday, March 20, 2015

Read N Characters Given Read4 -- Leetcode

Question:
The API: int read4(char *buf) reads 4 characters at a time from a file.
The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.
By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.
Note:
The read function will only be called once for each test case.



Answer:

// Forward declaration of the read4 API.
int read4(char *buf);

class Solution {
public:
    /**
     * @param buf Destination buffer
     * @param n   Maximum number of characters to read
     * @return    The number of characters read
     */
    int read(char *buf, int n) {

        int readNumRes=0;
        int m = n/4;
         
        for(int i=0;i<m;++i){
   
            int readNum = read4(buf);
            buf+=readNum;
            readNumRes+=readNum;
         
            if(readNum < 4){
                return readNumRes;     //return firstly!
            }
        }
     

        // Last several bytes should be condsider seperately, still has chars to read in the file
        int q = n%4;
        char tmpBytes[5];  //tmp bytes space for last read4(), space is 5, include '\0'!
       
        //For example: "ab", read(1); can not use read4(buf) directly, lastNum = 1, q=1, readNum=2 in the case!

        int readNum = read4(tmpBytes);
        int lastNum = q < readNum ? q : readNum;
     
        for(int i=0;i<lastNum;++i){
            *(buf+i) = tmpBytes[i];           //!important
        }
        readNumRes += lastNum;
        return readNumRes;
    }
};

Find Minimum in Rotated Sorted Array II -- Leetcode

Question:
Follow up for "Find Minimum in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
The array may contain duplicates.

Answer:

public class Solution {
    public int findMin(int[] num) {
       
        int start=0, end=num.length-1;
       
        while(start+1 < end){      //ensure: start != mid != end  
       
             int mid = start + (end-start)/2;
           
             if(num[mid] < num[end]){
                 end = mid;
             }
             else if(num[mid] > num[end]){
                 start = mid;
             }
             else{     //num[mid] == num[end], like [3 3 1 3]
           
                 int endtmp = end-1;
                 while(endtmp>mid && num[endtmp]==num[end]){
                     endtmp--;
                 }
                 if(num[endtmp] != num[mid]){     //there existeds peak point in the range!
                     start = mid;
                 }
                 else{
                     end = mid;     //include case: endtmp==mid, there are no peak point in the range!
                 }
             }
        }
       
        //start = end - 1
        if(num[start]<=num[end]){
            return num[start];
        }
        return num[end];
    }
}

Find Minimum in Rotated Sorted Array -- Leetcode

Question:
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
You may assume no duplicate exists in the array.

Answer:

public class Solution {
    public int findMin(int[] num) {
       
        int start=0, end=num.length-1;
       
        while(start+1 < end){      //ensure: start != mid != end  
             int mid = start + (end-start)/2;
           
             if(num[mid] < num[end]){
                 end = mid;
             }
             else{
                 start = mid;
             }
        }
       
        if(num[start]<num[end]){
            return num[start];
        }
        return num[end];
    }
}