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

};