Friday, November 25, 2016

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;
    }
};