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

Friday, November 4, 2016

Sort Characters By Frequency -- LeetCode

[Question]
Given a string, sort it in decreasing order based on the frequency of characters.
Example 1:
Input:
"tree"

Output:
"eert"

Explanation:
'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
Example 2:
Input:
"cccaaa"

Output:
"cccaaa"

Explanation:
Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.
Note that "cacaca" is incorrect, as the same characters must be together.
Example 3:
Input:
"Aabb"

Output:
"bbAa"

Explanation:
"bbaA" is also a valid answer, but "Aabb" is incorrect.
Note that 'A' and 'a' are treated as two different characters.
[Analysis]
First, use a hash table to count the frequency of each letter. Second, use a heap to sort each element in the hash table, based on the frequency. The time complexity is O(N). The space complexity can be constant, as there are fixed number of characters -- the size of heap is O(1).

[Solution]
class Solution {
public:
    string frequencySort(string s) {
        unordered_map<char, int> counter;
        auto comp = [](pair<char, int>& a, pair<char, int>& b) { return a.second <b.second; };
        priority_queue< pair<char,int>, vector<pair<char,int>>, decltype(comp) > sorter(comp);
       
        for(auto& c:s)
            counter[c]++;
           
        for(auto& p:counter)
            sorter.push(p);
       
        string res="";
        while (!sorter.empty()) {
            auto elem = sorter.top();
            sorter.pop();
            for (int i=0; i<elem.second; i++)
                res+=elem.first;
        }
       
        return res;
    }

};