Thursday, December 29, 2016

Range Sum Query - Mutable -- LeetCode 307

[Question]
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
The update(i, val) function modifies nums by updating the element at index i to val.
Example:
Given nums = [1, 3, 5]

sumRange(0, 2) -> 9
update(1, 2)
sumRange(0, 2) -> 8
Note:
  1. The array is only modifiable by the update function.
  2. You may assume the number of calls to update and sumRange function is distributed evenly.

[Analysis]
By using brute force on array itself, the update() can be achieved in O(1) and the sumRange() in O(N). It is not optimal when sumRange() to be called more often.

An alternative way is to use Segment Tree. The Segment Tree is heap like data structure. Both update() and sumRange() can be achieved in O(LogN). Extra O(N) space is used though.

Another range sum problem is "Count of Range Sum".

[Solution]
//
//-- Segment Tree --
//
class NumArray {
    vector<int> seg;
    int n;
public:
    NumArray(vector<int> &nums) {
        n = nums.size();
        seg.resize(n<<1);
        for (int i=n; i< (n<<1); i++)  seg[i] = nums[i-n];
        for(int i=n-1; i>0; i--) seg[i] = seg[i<<1] + seg[i<<1|1];
    }

    void update(int i, int val) {
        int diff = val-seg[i+n];
        for( i+=n; i>0; i>>=1 )
            seg[i] += diff;
    }

    int sumRange(int i, int j) {
        int res=0;
        for (i+=n, j+=n; i<=j; i>>=1, j>>=1) {
            if (i&1) res+=seg[i++];
            if (!(j&1)) res+=seg[j--];
        }
        return res;
    }
};

Tuesday, December 20, 2016

Word Break -- LeetCode 139

[Quesion]
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".

[Analysis]
Dynamic Programming: using one array A[n] to store whether first n letters of string s form a word sequence in dictionary, and A[0]= true,  A[i+1] will be true if A[j] == true and substr(j, i-j+1) is also a word in dictionary (0<=j<=i). The time complexity is O(N^2), space complexity is O(N).

DFS: try each prefix in dictionary recursively. Use a status memo to trim recursion branches.

Suppose Trie is built upon the word dictionary, Trie can help to get A[] initialized faster.

[Solution]
// -- Dynamic Programming --
class Solution {
public:
    bool wordBreak(string s, unordered_set<string>& wordDict) {
        vector<bool> res(s.size()+1, false);
        res[0]=true;
        for (int i=0; i<s.size(); i++)
            for (int j=i; j>=0; j--)     //-- faster than moving forward --
                if (res[j] && wordDict.count(s.substr(j,i-j+1)) ) {
                    res[i+1] = true;
                    break;
                }
        return res.back();
    }
};

// -- DFS --
class Solution {
    unordered_set<string> seen; // -- to record failed branches
public:
    bool wordBreak(string s, unordered_set<string>& wordDict) {
        if (wordDict.count(s)) return true;
        for (int i=0; i<s.size(); i++) {
            if (wordDict.count(s.substr(0,i+1)) ) {
                string ss = s.substr(i+1);
                if (seen.count(ss) ) continue;
                if (wordBreak(ss, wordDict))
                    return true;
                else seen.insert(ss);
            }
        }
        return false;
    }
};

Saturday, December 17, 2016

House Robber ||| -- LeetCode 337

[Question]
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night.
Determine the maximum amount of money the thief can rob tonight without alerting the police.
Example 1:
     3
    / \
   2   3
    \   \ 
     3   1
Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
     3
    / \
   4   5
  / \   \ 
 1   3   1
Maximum amount of money the thief can rob = 4 + 5 = 9.

[Analysis]
This is different from previous questions in this "House Robber" series. Assume S(n) is the max amount of money the robber can get at House[n],
       S(n) = max( S(n->left)+ S(n->right),
                H[n] + S(n->left->left) + S(n->left->right) + S(n->right->left) + S(n->right->right) )

So we can use DFS to accomplish this.

[Solution]
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    int helper(TreeNode* root, int &lsum, int &rsum) {
        if (root==NULL) return 0;
     
        int ll=0, lr=0, rl=0, rr=0;
        lsum = helper(root->left, ll, lr);
        rsum = helper(root->right, rl, rr);
        return max( lsum+rsum, root->val+ll+lr+rl+rr );
    }
public:
    int rob(TreeNode* root) {
        int lsum=0, rsum=0;
        return helper(root, lsum, rsum);
    }

};

House Robber II -- LeetCode 213

[Question]
Note: This is an extension of House Robber.
After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
[Analysis]
Assume S(0, n) is the largest amount the thief can get from circle houses H[0,..n], and R(x,y) is the largest amount from linear houses H[x, x+1,...y], then
    S(0,n) = max( R(0,n-1), R(1, n-2) + H[n]).

Since R(x,y) can be calculated using the solution in House Robber, S(0,n) is resolved.

[Solution]
//--- Solution #1 ---
class Solution {
    int robber(vector<int>& n, int lf, int rt) {
        int a=0, b=0, c=0;
        for (int i=lf; i<rt; i++) {
            c = max(b, a+n[i]);
            a=b, b=c;
        }
        return c;
    }
public:
    int rob(vector<int>& nums) {
        if (nums.empty()) return 0;
        int n= nums.size();
        return max( robber(nums, 0, n-1), robber(nums, 1, n-2)+ nums.back());
    }
};

//--- Solution #2 ---
class Solution {
public:
    int rob(vector<int>& nums) {
        if (nums.empty()) return 0;
        if (nums.size()==1) return nums[0];
     
        int a=0, b=nums[0], c=0;
        int x=0, y=0, z=0;
        int res;
        for (int i=1; i<nums.size(); i++) {
            c = max(b, a+nums[i]);  //R0(i)->c, b->R0(i-1)
            z = max(y, x+nums[i]);  //R1(i)->z, x->R1(i-2)

            res = max( x + nums[i], b);

            a=b, b=c;
            x=y, y=z;
        }
        return res;
    }

};


House Robber -- LeetCode 198

[Question]
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
[Analysis]
Assume the S(n) is the largest amount the robber can get from H[0,1,...n],
        S(n) = max(  S(n-1), S(n-2) + H[n] )
       
Further, we can assume there are two additional house before H[0], with zero assets. Use dynamic programming from the beginning of the Houses, we can S(0),... S(n). S(n) is the answer.

[Solution]
class Solution {
public:
    int rob(vector<int>& nums) {
        if (nums.empty()) return 0;

        int a=0, b=0, c=0;
        for (int i=0; i<nums.size(); i++) {
            c = max(b, a+nums[i]);
            a=b, b=c;
        }          
        return c;
    }

};

Thursday, December 15, 2016

Longest Repeating Character Replacement -- LeetCode 424

[Question]
Given a string that consists of only uppercase English letters, you can replace any letter in the string with another letter at most k times. Find the length of a longest substring containing all repeating letters you can get after performing the above operations.
Note:
Both the string's length and k will not exceed 104.
Example 1:
Input:
s = "ABAB", k = 2

Output:
4

Explanation:
Replace the two 'A's with two 'B's or vice versa.
Example 2:
Input:
s = "AABABBA", k = 1

Output:
4

Explanation:
Replace the one 'A' in the middle with 'B' and form "AABBBBA".
The substring "BBBB" has the longest repeating letters, which is 4.
[Analysis]
Use a sliding window [j,i] on the string. When the length of the window (i-j+1 - count of most repeating letters) <= k, move ending point i forward and the sub strings in the window are candidates. When the length - count of most repeating letters > k, move starting point j forward until the sub string in window contains the candidate.

Similar to the "Minimum Window Sub-String" problem.

[Solution]
class Solution {
public:
    int characterReplacement(string s, int k) {
        vector<int> counters(26,0);
        int j=0, max_cnt=0;
        int res = 0;
        for (int i=0; i<s.size(); i++) {
            counters[s[i]-'A']++;
            max_cnt = max(max_cnt, counters[s[i]-'A']);
            while (i-j+1 -max_cnt > k) {
                counters[s[j]-'A']--, j++;
                max_cnt = *max_element(counters.begin(), counters.end());
            }
            res = max(res, i-j+1);
        }

        return res;
    }
};

Thursday, December 8, 2016

Single Number III -- LeetCode

[Question]
Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
For example:
Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].
Note:
  1. The order of the result is not important. So in the above example, [5, 3] is also correct.
  2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
[Analysis]
By XOR all the elements, we can get the XOR result of the two single elements {A,B}. Since A!=B, there must one bit different between A and B. Therefore, divide all elements into two sets based on the bit value. XOR each set will give the two elements separately.

[Solution]
class Solution {
public:
    vector<int> singleNumber(vector<int>& nums) {
        int sum = accumulate (nums.begin(), nums.end(), 0, bit_xor<int>());
        int diff = sum & (-sum);
       
        vector<int> res = {0,0};
        for (auto n: nums) {
            if (n & diff) res[0]^=n;
            else res[1]^=n;
        }
        return res;
    }

};

Friday, December 2, 2016

Longest Increasing Path in a Matrix -- LeetCode

[Question]
Given an integer matrix, find the length of the longest increasing path.
From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).
Example 1:
nums = [
  [9,9,4],
  [6,6,8],
  [2,1,1]
]
Return 4
The longest increasing path is [1, 2, 6, 9].
Example 2:
nums = [
  [3,4,5],
  [3,2,6],
  [2,2,1]
]
Return 4
The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.

[Analysis]
Using DFS from each position of the matrix, travel on each possible paths, and get the maximum length that the position can reach. The length of path in each position can be reused. Therefore, an additional matrix is used to record the length information of each position. The time complexity and space complexity are both O(MxN), the size of matrix.

[Solution]
class Solution {
    vector<pair<int,int>> dd={{-1,0},{1,0},{0,1},{0,-1}};
 
    int searchPath(vector<vector<int>>& matrix, int i, int j, vector<vector<int>>& lens) {
        if (lens[i][j]!=0) return lens[i][j];
     
        int len=0;
        int temp = matrix[i][j];
        matrix[i][j] = INT_MIN;
        for (auto&d : dd) {
            int x = i+d.first, y=j+d.second;
            if (x>=0 && x<matrix.size() && y>=0 && y<matrix[0].size() && matrix[x][y]>temp) {
                len = max(len, searchPath(matrix, x, y, lens));
            }
        }
        matrix[i][j] = temp;
        lens[i][j] = 1 + len;
        return 1+len;
    }
public:
    int longestIncreasingPath(vector<vector<int>>& matrix) {
        if (matrix.empty()) return 0;
        vector<vector<int>> lens(matrix.size(), vector<int>(matrix[0].size(), 0));
     
        int res=1;
        for (int i=0; i<matrix.size(); i++) {
            for (int j=0; j< matrix[0].size(); j++) {
                res = max(res, searchPath(matrix, i, j, lens) );
            }
        }
        return res;
    }

};

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