Friday, February 7, 2014

Insert Interval

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].

Solution:
First try: insert the newInterval into given intervals, it causes multiple messy cases. Just think about put [2,8], [2,11] into Example 2. You have to find boundaries and decide what intervals are you going to combine. 
Think it in a different way, I then tried to insert all given intervals around the new interval. 
Basically, it has two cases:
1. no overlaps.
2. overlaps.
Please see code below for details.


public class Solution {
    public ArrayList insert(ArrayList intervals, Interval newInterval) {
        ArrayList result = new ArrayList();
        Interval cur = newInterval;
        for(Interval i : intervals){
            if(i.end < cur.start){
                result.add(i);
            }
            else if(i.start > cur.end){
                result.add(cur);
                cur = i;
            }
            else{
                int min = Math.min(i.start, cur.start);
                int max = Math.max(i.end, cur.end);
                cur.start = min;
                cur.end = max;
            }
        }
        result.add(cur);
        return result;
    }
}

No comments:

Post a Comment