Sunday, November 27, 2016

Partition Equal Subset Sum -- LeetCode 416

[Question]
Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
Note:
  1. Each of the array element will not exceed 100.
  2. The array size will not exceed 200.
Example 1:
Input: [1, 5, 11, 5]

Output: true

Explanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:
Input: [1, 2, 3, 5]

Output: false

Explanation: The array cannot be partitioned into equal sum subsets.

[Analysis]
This is a simplified Knapsack problem. The typical dynamic programming solution is to define dp[i][j] as if first i elements can get a sum of j, dp[0][0] is apparently true. The question becomes whether dp[n][m] is true, where n is the size of the input array and m is the half of the sum of n numbers. Furthermore,
        dp[i][j] = d[i-1][j]                       // if do not select the i-th element
                       || d[i-1][j- nums[i] ]      // if select the i-th element

Since the iteration of the dp calculation is along the i variable. The 2-dimension dp formula can be implemented by one dimensional array. Therefore, the space complexity is O(M), M is the sum of all numbers; the time complexity is O(NxM).

Interestingly, because of the assumption on array elements -- every element <=100 and the array size is <= 200 , the sum of whole array is less than 20,000.  There is a faster solution using bit manipulation to calculate all subset of the array. The bit manipulation approach can achieve the time complexity O(N) and space complexity O(M).

Derived from the bit manipulation, there is brute force approach to calculate all subset's sum using set but the time complexity will be O(2^N), much slower.

[Solution]
//-- Dynamic Programming O(NxM)  --
class Solution {
public:
    bool canPartition(vector<int>& nums) {
        //dp[i, j] -- first i elements can make a sum of j
        //dp[0,0]= true;
        //dp[i, j] = dp[i-1, j] || dp[i-1, j-A[i-1] ];
        int sum = accumulate(nums.begin(), nums.end(), 0);
        if (sum%2) return false;
        
        vector<bool> dp(sum/2+1, false);
        dp[0] = true;
        
        for (int i=0; i<nums.size(); i++)
            for (int j=dp.size()-1; j>0; j--)  // -- must be in reversed order. 
                dp[j]= dp[j] || j>=nums[i] && dp[ j-nums[i] ];
        return dp.back();
    }
};

//-- Back Tracking --
class Solution {
public:
    bool canPartition(vector<int>& nums) {
        int sum = 0;
        for(int i =0;i<nums.size();i++){
            sum+= nums[i];
        }
        if(sum%2) return false;
        sum /= 2;
        sort(nums.rbegin(),nums.rend());
        return helper(nums, sum, 0);
    }
    bool helper(vector<int>& nums, int sum, int index){
        if(sum == nums[index]) return true;
        if(sum < nums[index]) return false;
        return helper(nums,sum-nums[index],index+1) || helper(nums,sum,index+1);
    }
};

//-- Bit Manipulation O(N) --
class Solution {
public:
    bool canPartition(vector<int>& nums) {
        bitset<10001> bits(1);   // -- assume the max sum is 20,000.
        int sum = accumulate(nums.begin(), nums.end(), 0);
        for (auto n : nums) bits |= bits << n; 
        return !(sum & 1) && bits[sum >> 1];
    }
};

//-- Brute Force --
class Solution {
public:
    bool canPartition(vector<int>& nums) {
        unordered_set<int> sub;
        sub.insert(0);
     
        int sum  = accumulate(nums.begin(), nums.end(), 0);
        if ((sum %2) == 1) return false;
     
        for (auto n: nums) {
            unordered_set<int> temp;
            for (auto x:sub) {
                temp.insert(x+n);
            }
            sub.insert(temp.begin(), temp.end());
        }
     
        return sub.count(sum/2);
    }
};

Friday, November 25, 2016

Word Search II -- 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.

[Analysis]
This is a typical Back Tracking problem. Using DFS to explore every letter on the board. Trie can be used to trim the branches of DFS -- no need to travel on string path which is not a prefix of any words in the target set. The time complexity is O(MxNxL) L is the number of nodes in Trie.

[Solution]
class TrieNode {
public:
    bool isWord;
    vector<TrieNode *> letters;
    // Initialize your data structure here.
    TrieNode(): isWord(false) {
        letters.resize(26, NULL);
    }
};

class Trie {
public:
    Trie() {
        root = new TrieNode();
    }

    // Inserts a word into the trie.
    void insert(string word) {
        TrieNode* p=root;
        for (auto c: word) {
            int i =c-'a';
            if (!p->letters[i])
                p->letters[i] = new TrieNode();
            p = p->letters[i];
        }
        p->isWord = true;
    }

    // Returns if the word is in the trie.
    bool search(string word) {
        TrieNode* p=root;
        for (auto c: word) {
            int i = c-'a';
            if (!p->letters[i]) return false;
            p = p->letters[i];
        }
        return p->isWord;
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    bool startsWith(string prefix) {
        TrieNode* p=root;
        for (auto c: prefix) {
            int i = c-'a';
            if (!p->letters[i]) return false;
            p = p->letters[i];
        }
        return true;
    }

    TrieNode* getRoot() {
        return root;
    }
private:
    TrieNode* root;
};

class Solution {
    Trie trie;
    int limit;
    vector<pair<int,int>> dd = {{0,1},{0,-1},{1,0},{-1,0}};  
   
    void searchWords( vector<vector<char>>& b, int i, int j, string s, TrieNode* p, set<string>& res) {
        char cur = b[i][j];
        if (s.size() == limit) return;
        p = p->letters[cur-'a'];
        if (p==NULL) return;
        if (p->isWord) res.insert(s+cur);

        b[i][j] = ' ';
        for (auto& d : dd) {
            int x = i+d.first, y=j+d.second;
            if ( 0<=x && x<b.size() && 0<=y && y<b[0].size() && b[x][y]!=' ' )
                searchWords(b, x, y, s+cur, p, res);
        }
        b[i][j]= cur;
    }
public:
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        limit = 0;
        for (auto& w: words) {
            trie.insert(w);
            limit = max(limit, (int)w.size() );
        }
       
        set<string> res;
        for (int i=0; i<board.size(); i++)
            for (int j=0; j<board[0].size(); j++) {
                searchWords( board, i, j, "", trie.getRoot(), res);
            }
        return vector<string>(res.begin(),  res.end());
    }

};

Elimination Game -- LeetCode

[Question]
There is a list of sorted integers from 1 to n. Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.
Repeat the previous step again, but this time from right to left, remove the right most number and every other number from the remaining numbers.
We keep repeating the steps again, alternating left to right and right to left, until a single number remains.
Find the last number that remains starting with a list of length n.
Example:
Input:
n = 9,
1 2 3 4 5 6 7 8 9
2 4 6 8
2 6
6

Output:
6
[Analysis]
The value of the last remaining number is equal to the position of that number in the original array. Think the process in backward: assume x is in position i in round n, then what is the position of x should be in the previous round n-1?
     1) If n-1 is odd, the x must be in 2*i position in round n-1.
     2) If n-1 is even, and the count of  number in round n-1 is even, the position of  x must be in 2*i-1 in round n-1.
     3) If n-1 is even, and the count of number in round n-1 is odd, the position of x must be in 2*i in round n-1.

Therefore, we can trace backward from position 1 (last remaining) to the position of the number in original array. The time complexity is O(Log N), the space complexity is O(Log N) -- space can be reduced to O(1) as it is only needed for the count of numbers in each round.

[Solution]
class Solution {
public:
    int lastRemaining(int n) {
        int res = 1;

        stack<int> nums;
        while (n>1) {
            nums.push(n);
            n/=2;
        }
        while (!nums.empty()) {
            if (nums.size() % 2==0 && nums.top()%2==0)
                res = res*2-1;
            else
                res *=2;
            nums.pop();
        }
        return res;
    }
};

Random Numbers with Exceptions

[Question]
Write a function to generate random numbers in [0, N-1], excluding numbers in a given list. For example, N=10, the excluding list is {4, 6, 9}, then a random number is valid when it is not 4, or 6, or 9.

[Analysis]
This is another question that Reservior Sampling can be applied. The generator function will exclude the numbers in the range and give the equal possibility to the rest.

When there is only one number is excluded, the solution can be as simple as, generate one number from [0, N-2], if the generated number is equal to the excluded number, return N-1. This is a special case of Reservior Sampling.

[Solution]
int rand_except(int n, unordered_set<int>& exp) {
     int res=-1, count=0;
     for (int i=0; i<n; i++) {
          if (exp.count(i)>=0) continue;
          if ( rand()%(++count)==0 ) res = i;
     }
     return res;
}

Linked List Random Node -- LeetCode

[Question]
Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen.
Follow up:
What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space?
Example:
// Init a singly linked list [1,2,3].
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
Solution solution = new Solution(head);

// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
solution.getRandom();

[Analysis]
Another Reservior Sampling problem. The run time is at O(N) without additional space expense. See also the similar question Random Pick Index.

[Solution]
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    ListNode* head;
public:
    /** @param head The linked list's head.
        Note that the head is guaranteed to be not null, so it contains at least one node. */
    Solution(ListNode* head): head(head) {
    }
 
    /** Returns a random node's value. */
    int getRandom() {
        int res;
         for (int cnt=1,  ListNode* p = head;  p;  p=p->next, cnt++)
              if (rand()%cnt == 0) res = p->val;
     
        return res;
    }

};

Random Pick Index -- LeetCode

[Question]
Given an array of integers with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.
Note:
The array size can be very large. Solution that uses too much extra space will not pass the judge.
Example:
int[] nums = new int[] {1,2,3,3,3};
Solution solution = new Solution(nums);

// pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
solution.pick(3);

// pick(1) should return 0. Since in the array only nums[0] is equal to 1.
solution.pick(1);

[Analysis]
This is a typical Reservior Sampling problem. Usually, it is used to when data set is too large to feed into memory. The time complexity of pick() is O(N). The additional space is O(1).

[Solution]
class Solution {
    vector<int> n;
public:
    Solution(vector<int> nums): n(nums) {
    }
 
    int pick(int target) {
        int count=0, res=-1;
        for (int i=0; i<n.size(); i++) {
            if (n[i]!=target) continue;
            if (rand() % (++count) ==0) res=i;
        }
        return res;
    }

};

Thursday, November 24, 2016

Line Reflection -- LeetCode

[Question]
Given n points on a 2D plane, find if there is such a line parallel to y-axis that reflect the given set of points.
Example 1:
Given points = [[1,1],[-1,1]], return true.
Example 2:
Given points = [[1,1],[-1,-1]], return false.
Follow up:
Could you do better than O(n2)?
Hint:
  1. Find the smallest and largest x-value for all points.
  2. If there is a line then it should be at y = (minX + maxX) / 2.
  3. For each point, make sure that it has a reflected point in the opposite side.

[Analysis]
Suppose the reflection line is x', since each point (x,y) should have its reflection point (x' + x'-x, y) in the input array.  The x' can be calculated by (minX+maxX)/2, or by the average of all x of points. The time complexity is O(N).

[Solution]
class Solution{
    bool isReflected ( vector<pair<int,int>>& points ) {
        if (points.empty()) return true;
        unordered_set<pair<int,int>> pts;
        double line = 0;
        for (auto &p : points) {  
            line += p.first;
            pts.insert( p );
        }
        line /= points.size();
        for (auto& p: points) {
            if (!pts.count( {line + line-p.first, psecond} )  ) return false;
        }
        return true;
     }
};

 

132 Pattern -- LeetCode 456

[Question]
Given a sequence of n integers a1, a2, ..., an, a 132 pattern is a subsequence ai, aj, ak such that i < j < k and ai < ak < aj. Design an algorithm that takes a list of n numbers as input and checks whether there is a 132 pattern in the list.
Note: n will be less than 15,000.
Example 1:
Input: [1, 2, 3, 4]

Output: False

Explanation: There is no 132 pattern in the sequence.
Example 2:
Input: [3, 1, 4, 2]

Output: True

Explanation: There is a 132 pattern in the sequence: [1, 4, 2].
Example 3:
Input: [-1, 3, 2, 0]

Output: True

Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].
[Analysis]
Use a Set (binary search tree) to collect uphill ranges from the beginning of the array. For the next number in array, use Binary Search to the the range that might be a 132 pattern. If not, the number will form a new range and be put into the Set. The trick to form a range to use a variable 'low' to track the lowest value so far in the array.

Another solution is to think about the 132 pattern in back-forward, which is 231 pattern. It is much simpler because there is no need to record the ranges. As long as we '23' pattern is tracked, largest '2' is recorded and the new coming number is smaller than '2', the return is true. This time complexity is O(N).

[Solution]
//-- sol.#1: Binary Search --
class Solution {
public:
    bool find132pattern(vector<int>& nums) {
        int low = INT_MAX;
        auto comp = []( pair<int,int> a, pair<int,int> b ) { return a.second < b.second;};
        set<pair<int,int>, decltype(comp)> pairs (comp);
     
        for(auto n: nums) {
            if (!pairs.empty()) {
                auto it = pairs.upper_bound({n,n});
                if (it!=pairs.end() && it->first<n && n<it->second)
                    return true;
                pairs.erase( pairs.begin(), it );
            }
            low = min(low,n);
            if (low< n) pairs.insert( {low, n});
        }
        return false;
    }
};

//-- sol. #2 Stack --
class Solution {
public:
    bool find132pattern(vector<int>& nums) {
        if (nums.size()<3) return false;
        
        stack<int> st; 
        int third = INT_MIN;
        for (int i= nums.size()-1; i>=0; i--) {
            if (nums[i] < third) return true;
            else {
                while (!st.empty() && nums[i]>st.top()) {
                    third = st.top(); st.pop();
                }
            }
            st.push(nums[i]);
        }
        return false;
    }
};

Monday, November 21, 2016

Palindrome Pairs -- LeetCode

[Question]
Given a list of unique words, find all pairs of distinct indices (i, j) in the given list, so that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome.
Example 1:
Given words = ["bat", "tab", "cat"]
Return [[0, 1], [1, 0]]
The palindromes are ["battab", "tabbat"]
Example 2:
Given words = ["abcd", "dcba", "lls", "s", "sssll"]
Return [[0, 1], [1, 0], [3, 2], [2, 4]]
The palindromes are ["dcbaabcd", "abcddcba", "slls", "llssssll"]
[Analysis]
Brute force will do it in O(NxNxM), N is the number of strings in the list and M is the average length of those strings.
To lower the time complexity, use a hash table to reduce the comparison time and sort the length of strings to reduce the candidates for comparison. For each word S, compare with only words S' that are shorter. Since S' should be in the hash table, the only thing left is to make sure S- reversed(S') is a palindrome.

[Solution]
class Solution {
public:
    vector<vector<int>> palindromePairs(vector<string>& words) {
        unordered_map<string, int> pos;
        set<int> lens;
     
        for(int i=0; i<words.size(); i++) {
            pos[words[i]] = i;
            lens.insert(words[i].size());
        }
     
        auto isPal =[] (string& s, int pos, int len) {
            for (int i=pos, j=pos+len-1; i<j; i++,j-- )
                if (s[i]!=s[j]) return false;
            return true;
        };
     
        vector<vector<int>> res;
        for (int i=0; i<words.size(); i++) {
            string s = words[i];
            string rev=s;
            int s_len = s.size();
            reverse( rev.begin(), rev.end() );
         
            if (pos.count(rev) && pos[rev]!=i)
                res.push_back({i, pos[rev]});
         
            for (auto it=lens.begin(); *it<s_len; it++) {
                int len = *it;
                if (pos.count(rev.substr(0, len)) && isPal(s, 0, s_len-len ))
                    res.push_back({pos[rev.substr(0, len)], i});
             
                if (pos.count(rev.substr(s_len-len, len)) && isPal(s, len, s_len-len) )
                    res.push_back({i, pos[rev.substr(s_len-len, len)]});
            }
        }
     
        return res;
    }
};

Wednesday, November 16, 2016

Number of Islands -- LeetCode 200

[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
[Analysis]
Scanning through each position in the grid, if there is an '1', use BFS and find all '1' in this island. Then find another '1' for another island. The time complexity is O(MxN). 
Using DFS is also good and easier to implement. 
[Solution]
//
//--- BFS ---
//
class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        if (grid.empty()) return 0;
        
        int m=grid.size(), n=grid[0].size();
        int count=0;
        
        auto expand=[&grid, m, n](int x, int y) {
            queue<pair<int,int>> que;
            vector<pair<int,int>> dir = {{0,1}, {1,0},{0,-1},{-1,0}};
            
            que.push({x,y}); grid[x][y]=0;
            while (!que.empty()) {
                auto loc = que.front();
                que.pop();
                
                for (auto d: dir) {
                    int nx=loc.first+d.first, ny=loc.second+d.second;
                    if (nx>=0 &&nx<m && ny>=0 && ny<n && grid[nx][ny]=='1') {
                        que.push({nx,ny}); grid[nx][ny]=0;
                    }
                }
            }
        };
        
        for (int i=0; i<m; i++) 
            for (int j=0; j<n; j++) {
                if (grid[i][j]=='1') {
                    expand(i, j);
                    count++;
                }
            }
        return count;
    }
};

//
//--- DFS ---
//
class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        if (grid.empty()) return 0;
        
        int m=grid.size(), n=grid[0].size();
        function<int(int,int)> dfs = [&] (int i, int j) {
            if (i<0||i>=m||j<0 || j>=n || grid[i][j]=='0') return 0;
            grid[i][j]='0';
            dfs(i+1,j); dfs(i-1,j); dfs(i,j+1); dfs(i,j-1);
            return 1;
        };
        
        int count=0;
        for(int i=0; i<m; i++) 
            for (int j=0; j<n; j++)
                count+= dfs(i, j);
                
        return count;
    }
};

Frog Jump -- LeetCode

[Question]
A frog is crossing a river. The river is divided into x units and at each unit there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.
Given a list of stones' positions (in units) in sorted ascending order, determine if the frog is able to cross the river by landing on the last stone. Initially, the frog is on the first stone and assume the first jump must be 1 unit.
If the frog's last jump was k units, then its next jump must be either k - 1, k, or k + 1 units. Note that the frog can only jump in the forward direction.
Note:
  • The number of stones is ≥ 2 and is < 1,100.
  • Each stone's position will be a non-negative integer < 231.
  • The first stone's position is always 0.
Example 1:
[0,1,3,5,6,8,12,17]

There are a total of 8 stones.
The first stone at the 0th unit, second stone at the 1st unit,
third stone at the 3rd unit, and so on...
The last stone at the 17th unit.

Return true. The frog can jump to the last stone by jumping 
1 unit to the 2nd stone, then 2 units to the 3rd stone, then 
2 units to the 4th stone, then 3 units to the 6th stone, 
4 units to the 7th stone, and 5 units to the 8th stone.
Example 2:
[0,1,2,3,4,8,9,11]

Return false. There is no way to jump to the last stone as  
the gap between the 5th and 6th stone is too large.

[Analysis]
Assume stones' positions as P(i),  and the jump to P(i) is S(i), i=0...n. Whether P(i) is reachable from P(j), 0<=j<i, depends on two factors:
      1) whether P(j) is reachable and
      2) whether the last jump to P(j):  is S(j)-1 <= P(i)-P(j)<= S(j)+1

Counting from the beginning of the position, we could collect all possible S(j) for each position. If the last position of P(last) has possible jumps, i.e. S(last) is not empty, the frog jump will succeed.

The process can be illustrated as this:
P: [0, 1, 3, 5, 6, 8,  12]
S:      S(1)= {1}, S(2)={2}, S(3)={2}, S(4)={1,3}, S(5)={1,2,3}, S(6)={4} -- succeeded.

[Solution]
class Solution {
public:
    bool canCross(vector<int>& stones) {
        unordered_map<int, unordered_set<int>> steps;
     
        for (auto& s: stones) steps[s] = {};
        steps[1].insert(1);

        for (int i=1; i<stones.size()-1; i++) {
            int pos = stones[i];
            for (auto& s: steps[pos]) {
                int npos = pos + s -1;
                if (npos!=pos && steps.count(npos))  steps[npos].insert(s-1);
                if (steps.count(npos+1)) steps[npos+1].insert(s);
                if (steps.count(npos+2)) steps[npos+2].insert(s+1);
            }
        }
        return !steps[stones.back()].empty();
    }

};

Sunday, November 13, 2016

Minimum Genetic Mutation -- LeetCode

[Question]
A gene string can be represented by an 8-character long string, with choices from "A""C""G""T".
Suppose we need to investigate about a mutation (mutation from "start" to "end"), where ONE mutation is defined as ONE single character changed in the gene string.
For example, "AACCGGTT" -> "AACCGGTA" is 1 mutation.
Also, there is a given gene "bank", which records all the valid gene mutations. A gene must be in the bank to make it a valid gene string.
Now, given 3 things - start, end, bank, your task is to determine what is the minimum number of mutations needed to mutate from "start" to "end". If there is no such a mutation, return -1.
Note:
  1. Starting point is assumed to be valid, so it might not be included in the bank.
  2. If multiple mutations are needed, all mutations during in the sequence must be valid.
  3. You may assume start and end string is not the same.
[Analysis]
The gene strings can construct a graph with each node is an gene and each edge is a valid mutation. Then the problem becomes find a path from start node to the end node. This can be done with BFS and time complexity is O(N).

The construction of the graph needs to compare every two nodes, which makes the time complexity O(N^2). Since the gene string is an 8-character string with only 4 letters, instead of constructing a graph, we can use all valid mutation of a given string when probing the next possible gene. There only 31(4x8-1) possibilities. Therefore, the overall time complexity can be still O(N).

The sample code #1 constructed a graph and code #2 just enumerated the 31 possible mutations.

[Solution]
//-- code #1 with building a graph --
class Solution {
    bool oneMutation( const string& a, const string& b ) {
        if (a.size()!=8 && a.size()!=b.size()) return false;
     
        int count=0;
        for (int i=0; i<8; i++) {
            count += (a[i]!=b[i]);
        }
        return (count==1);
    }
 
public:
    int minMutation(string start, string end, vector<string>& bank) {
        int s=bank.size(),e=-1;
     
        for (int i=0; i<bank.size(); i++) {
            if (bank[i].compare(start)==0) s=i;
            if (bank[i].compare(end)==0) e=i;
        }
        if (e==-1) return -1;
        if (s==bank.size()) bank.push_back(start);
     
        vector<vector<int>> grph(bank.size(), vector<int>() );
        for (int i=0; i<bank.size(); i++) {
            for (int j=i+1; j<bank.size(); j++) {
                if (oneMutation(bank[i], bank[j]) ) {
                    grph[i].push_back(j);
                    grph[j].push_back(i);
                }
            }
        }
     
        unordered_set<int> visited;
        queue<int> que; int step=1;
        que.push(s);  que.push(INT_MAX);
        while (!que.empty()) {
            int cur = que.front();
            que.pop();
         
            if (cur==INT_MAX) {
                step++;
                if (que.empty()) break;
                else {
                    que.push(INT_MAX);
                    continue;
                }
            }
            visited.insert(cur);
            for(auto n: grph[cur]) {
                if (n==e) return step;
                if (visited.count(n)==0) que.push(n);
            }
        }
        return -1;
    }

};

//-- Code #2  without graph, using enumeration --
class Solution {
    int to_int(string gene) {
        static unordered_map<char, int> gmap ({{'A',0},{'C',1},{'G',2}, {'T',3}});
        int res=0;
        for(int i=0; i<8; i++) {
            res = res<<2 | gmap[ gene[i] ];
        }
        return res;
    }
 
public:
    int minMutation(string start, string end, vector<string>& bank) {
        unordered_set<int> gbank;
        for (int i=0; i<bank.size(); i++) {
            gbank.insert(to_int(bank[i]));
        }
        if ( gbank.count(to_int(end)) == 0 ) return -1;
     
        queue<int> que;
        que.push(to_int(start));
        que.push(INT_MAX);
        int step=1;
        int e=to_int(end);
        while (!que.empty()) {
            int cur = que.front();
            que.pop();

            if (cur==INT_MAX && que.empty()) break;
            if (cur==INT_MAX) {
                step++;
                que.push(INT_MAX);
                continue;
            }
         
            for (int i=0; i<8; i++) {
                for (int j=0; j<4; j++) {
                    int next = cur  ^ (j << 2*i);
                    if (gbank.count( next ) != 0) {
                        if (next==e) return step;
                        que.push( next );
                        gbank.erase( next );
                    }
                }
            }
        }
        return -1;
    }
};

Saturday, November 12, 2016

Meeting Room II -- LeetCode

[Question]
Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required.
For example, Given [[0, 30],[5, 10],[15, 20]], return 2.
[Analysis]
This is another interval related problem. First, we can sort all the starts (s1, s2, ...) and ends (e1, e2, ...) into two series. Then, for each ends 'e', count how many starts are before 'e' -- that is how many rooms we need before time 'e'. Time complexity is O(N Log N), space complexity is O(N).

The similar problems: "Non-overlapping Intervals", "Minimum Number of Arrows to Burst Balloons".

[Solution]
public class Solution {
    public int minMeetingRooms(vector<Interval> intervals) {
        vector<int> starts(intervals.size(), 0);
        vector<int> ends(intervals.size(), 0);
        for (int i=0; i<intervals.size(); i++) {
            starts[i] = intervals[i].start;
            ends[i] = intervals[i].end;
        }
        sort (starts.begin(), starts.end());
        sort(ends.begin(), ends.end());
        int room=0; int j=0;
        int res =0;
        for (auto e: ends) {
            while (starts[j]<e) {
                j++; room++;
                res = max(res, room);
            }
            room--;
         }
         return res;
    }
}

//
// Using Hash Table
//
class Solution {
public:
    int minMeetingRooms(vector<Interval>& intervals) {
        map<int, int> m;
        for (auto a : intervals) {
            m[a.start]++;
            m[a.end]--;
        }
        int rooms = 0, res = 0;
        for (auto it : m) {
            res = max(res, rooms += it.second);
        }
        return res;
    }
};

Non-overlapping Intervals -- LeetCode 435

[Question]
Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Note:
  1. You may assume the interval's end point is always bigger than its start point.
  2. Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other.
Example 1:
Input: [ [1,2], [2,3], [3,4], [1,3] ]

Output: 1

Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.
Example 2:
Input: [ [1,2], [1,2], [1,2] ]

Output: 2

Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.
Example 3:
Input: [ [1,2], [2,3] ]

Output: 0

Explanation: You don't need to remove any of the intervals since they're already non-overlapping.
[Analysis]
This problem is equivalent to the problem "Minimum Number of Arrows to Burst Balloons". Instead of counting the overlapping intervals, this problem needs to calculate the number of redundant intervals.

The basic idea is to use a greedy approach. 1) sort the intervals by the ends; 2) suppose we have a few selected non-overlapping intervals, use the end of  the last interval X as a vertical scan line from left to right: any intervals with start that is smaller than the scan line will be overlapped with X, therefore, place the first non-overlapping interval X1 into selected list and repeat 2).

[Solution]
class Solution {
public:
    int eraseOverlapIntervals(vector<Interval>& intervals) {
        auto comp = [](Interval a, Interval b) { return a.end==b.end && a.start<b.start|| a.end<b.end;};
        sort(intervals.begin(), intervals.end(), comp);
     
        int count=0, line = INT_MIN;
        for(auto& e: intervals) {
            if (e.start< line ) continue;
            count++;
            line = e.end;
        }
        return intervals.size()-count;
    }
};

Friday, November 11, 2016

Minimum Number of Arrows to Burst Balloons -- LeetCode

[Question]
There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided input is the start and end coordinates of the horizontal diameter. Since it's horizontal, y-coordinates don't matter and hence the x-coordinates of start and end of the diameter suffice. Start is always smaller than end. There will be at most 104 balloons.
An arrow can be shot up exactly vertically from different points along the x-axis. A balloon with xstart and xend bursts by an arrow shot at x if xstart ≤ x ≤ xend. There is no limit to the number of arrows that can be shot. An arrow once shot keeps travelling up infinitely. The problem is to find the minimum number of arrows that must be shot to burst all balloons.
Example:
Input:
[[10,16], [2,8], [1,6], [7,12]]

Output:
2

Explanation:
One way is to shoot one arrow for example at x = 6 (bursting the balloons [2,8] and [1,6]) and another arrow at x = 11 (bursting the other two balloons).
[Analysis]
First, sort the balloons by the end of their end of the diameter suffice.  Then, using those ends as the positions to shot the arrow and all those balloons whose 'start'  <=  'the current arrow position', will burst. The time complexity is O(N LogN) due to sorting, the space complexity is O(1).

[Solution]
class Solution {
public:
    int findMinArrowShots(vector<pair<int, int>>& points) {
        if (points.size()<2) return points.size();
       
        #define PT pair<int,int>        
        auto comp = [](PT& a, PT& b) { return (a.second==b.second)?a.first<b.first: a.second<b.second; };
        sort(points.begin(), points.end(), comp);
       
        int count=0, arrow=INT_MIN;
        for (auto& p:points) {
            if (p.first<=arrow) continue;
            count++, arrow=p.second;
        }
        return count;
    }
};