Showing posts with label Intervals. Show all posts
Showing posts with label Intervals. Show all posts

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

Thursday, June 9, 2016

Data Stream as Disjoint Intervals -- LeetCode

[Question]
Given a data stream input of non-negative integers a1, a2, ..., an, ..., summarize the numbers seen so far as a list of disjoint intervals.
For example, suppose the integers from the data stream are 1, 3, 7, 2, 6, ..., then the summary will be:
[1, 1]
[1, 1], [3, 3]
[1, 1], [3, 3], [7, 7]
[1, 3], [7, 7]
[1, 3], [6, 7]

[Analysis]
Given a new number A, using Binary Search Tree can find the relevant intervals in O(LogN) time complexity, where N is the number of collected intervals. The relevant intervals are the 'previous' and 'next' intervals, closest intervals to A and their 'end' values are smaller or larger(or equal to) than A, respectfully. In C++, the data structure BST can use 'std::set', 'std::map' in STL.

The 'std::map' may provide an easier implementation. Define map<int,int>, map[end]=start for interval [start,end]. Use lower_bound() to quickly (O(LogN)) check the position where a new number will end up with.

[Solution]
/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */
class SummaryRanges {
    map<int, int> buf;
   
public:
    /** Initialize your data structure here. */
    SummaryRanges() {
    }
   
    void addNum(int val) {
        if (buf.empty()) {
            buf[val]=val;
            return;
        }
       
        auto it=buf.lower_bound( val );
        if (it==buf.end())
            buf[val]=(buf.count(val-1))?buf[val-1]:val;
        else {
            if (it->second <= val) return;
            if (it->second  == val+1)
                it->second = (buf.count(val-1))?buf[val-1]:val;
            else
                buf[val]=(buf.count(val-1))?buf[val-1]:val;
        }
        buf.erase(val-1);
    }
   
    vector<Interval> getIntervals() {
        vector<Interval> res;
       
        for (auto& pr: buf)
            res.push_back( Interval(pr.second, pr.first) );
        return res;
    }
};

//
// Another solution if getIntervals() is less frequently called.
//
class SummaryRanges {
    set<int> buf;
 
public:
    /** Initialize your data structure here. */
    SummaryRanges() {
    }
 
    void addNum(int val) {
        buf.insert(val);
    }
 
    vector<Interval> getIntervals() {
        vector<Interval> res;
        int start=-1, end=-1;
        for (auto& n: buf) {
            if (res.empty()|| n!=res.back().end+1)
                res.push_back(Interval(n, n));
            if (n == res.back().end+1)
                res.back().end=n;
        }
        return res;
    }
};

Friday, December 5, 2014

Insert Interval -- Leetcode

[Question]
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.

Example 1:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].

Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].
This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
[Analysis]
Because all intervals are sorted and non-overlapping, for intervals A and B, if A.start < B.start, A.end < B.end.  Need to find the first and the last interval in the sequence that overlaps with the given interval.

One scan on the array of intervals can complete the replacement. Time complexity is O(N). There is no need for extra storage (shown in the 2nd code sample below). The 3rd code sample shows how binary search can help to improve time complexity of locating the overlapping range of intervals.

[Solution]
/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */
//---  (1) This solution use O(N) extra storage.
//---        The input intervals vector is not changed
class Solution {
public:
    vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
        if (intervals.empty())  return vector<Interval>(1, newInterval);
     
        vector<Interval> ret;
        int i,j;
        for (i=0; i<intervals.size(); i++) {
            if (intervals[i].end < newInterval.start) {
                ret.push_back(intervals[i]);
            }
            else break;
        }
     
        for (j=intervals.size()-1; j>=0; j--) {
            if (intervals[j].start <= newInterval.end)
                break;
        }          
     
        if (i<=j)  {
            newInterval.start = min (newInterval.start, intervals[i].start);
            newInterval.end = max (newInterval.end, intervals[j].end);
        }
        ret.push_back(newInterval);
     
        for (int k=j+1; k< intervals.size(); k++) {
            ret.push_back( intervals[k] );
        }
     
        return ret;
    }
};

//--- (2) This solution is in-place.
//---       The input "intervals" are modified accordingly.
class Solution {
public:
    vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
        if (intervals.empty()) {
            intervals.push_back(newInterval);
            return intervals;
        }
     
        if (intervals[0].start > newInterval.end) {
            intervals.insert (intervals.begin(), newInterval);
            return intervals;
        }
     
        if (intervals.back().end < newInterval.start) {
            intervals.push_back(newInterval);
            return intervals;
        }
     
        int iStart = 0;
        for (int i=0; i<intervals.size(); i++) {
            if (newInterval.start <= intervals[i].end) {
                iStart = i;
                break;
            }
        }

        int iEnd = 0;
        for (int i=intervals.size()-1; i>=0; i--) {
            if (newInterval.end >= intervals[i].start) {
                iEnd = i;
                break;
            }
        }
             
        newInterval.start = min(newInterval.start, intervals[iStart].start);
        newInterval.end   = max(newInterval.end, intervals[iEnd].end);
     
        intervals.erase(intervals.begin()+iStart, intervals.begin()+iEnd+1);
        intervals.insert(intervals.begin()+iStart, newInterval);
     
        return intervals;
    }
};

//--- (3) Use binary search: lower_bound() in STL.
class Solution {
public:
    vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
        if (intervals.empty()) {
            intervals.push_back(newInterval);
            return intervals;
        }
     
        if (intervals[0].start > newInterval.end) {
            intervals.insert (intervals.begin(), newInterval);
            return intervals;
        }
     
        if (intervals.back().end < newInterval.start) {
            intervals.push_back(newInterval);
            return intervals;
        }

        int iStart = lower_bound(intervals.begin(), intervals.end(), newInterval,
                [](const Interval& a, const Interval& t) { return t.start > a.end; } ) - intervals.begin();
     
        int iEnd = lower_bound(intervals.begin(), intervals.end(), newInterval,
                [](const Interval& a, const Interval& t) { return t.end >= a.start; } ) - intervals.begin()-1;
             
        newInterval.start = min(newInterval.start, intervals[iStart].start);
        newInterval.end   = max(newInterval.end, intervals[iEnd].end);
     
        intervals.erase(intervals.begin()+iStart, intervals.begin()+iEnd+1);
        intervals.insert(intervals.begin()+iStart, newInterval);
     
        return intervals;
    }
};

Wednesday, December 3, 2014

Merge Intervals -- Leetcode

[Question]
Given a collection of intervals, merge all overlapping intervals.

For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].

[Analysis]

If all intervals are sorted by their start points, the overlapping between two consecutive intervals A and B is simple: A.end > B.start. If B.start> A.end, B and the following intervals have no overlapping with A. Therefore, sort the intervals first, then scan the sorted interval list and merge them one by one when possible. The time complexity is O(N x log N + N).

Without sorting, the overlapping cases among intervals are complicated. It can not be done by one pass.

[Solution]
/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */
class Solution {
public:
    bool intersected( const Interval& a, const Interval& b) {
        return !(a.start>b.end || b.start>a.end);
    }
 
    vector<Interval> merge(vector<Interval> &intervals) {
        if (intervals.empty()) return intervals;
       
        sort(intervals.begin(), intervals.end(),
            [](Interval a, Interval b) { return a.start < b.start; }
        );
       
        int size = intervals.size();
        Interval temp (intervals[0].start, intervals[0].end);
        for (int i=1; i<size; i++) {
            if ( intersected(intervals[i], temp) ){
                temp.start = min(intervals[i].start, temp.start);
                temp.end = max(intervals[i].end, temp.end);
            }
            else {
                intervals.push_back(temp);
                temp = intervals[i];
            }
        }
        intervals.push_back(temp);
        intervals.erase(intervals.begin(), intervals.begin()+size);
        return intervals;
    }
};