Problem
Given a collection of intervals, merge all overlapping intervals.
Example 1:
1 |
|
Example 2:
1 |
|
NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
Explanation 1
-
We can change the input intervals to the following intervals: first start match the first end as one new interval, second start match the second end as one new interval, third start match the third interval as one new interval, etc. After changing, these intervals will have the same characteristic as the input intervals. For example, merging interval will have the same starting point and ending pointing, and their overlapping interval will be the same too.
1
2
3
4
5
6
7
8
9
10
11
12
13original interval: (1st)- - - - - - - - - - - - - - - - - -(3en) (3st)- - - - - - - - - -(2en) (2st)- - - - - - - -(1en) (4st)- - - - - - - - - - - - -(4en) new created sort intervals: (1st)- - - - - - - - - - - -(1en) (2st)- - - - - - - - - - — -(2en) (3st)- - - - - - - - — - - -(3en) (4st)- - - - - — - - - - — - -(4en) Before sort, all interval’s merge interval will be the same as the new created sorted merge interval.
-
We can create a start array to hold all sorted starting points, and one end array to holds all sorted ending points. For example,
start[] = {1, 4, 6, 8}
,end[] = {2, 7, 9, 10}
, then we create four intervals:{1, 2}, {4, 7}, {6, 9}, {8, 10}
like the following:1
2
3
4
5
6(1, 2)- - - - (4, 7)- - - - - - - - (6, 9)- - - - - - - - (8, 10)- - - - - - start:[1, 4, 6, 8] end:[2, 7, 9, 10]
-
From the above example, we can see the first end 2 is less than the second start 4, so they are not overlapping. The second end 7 is greater than the third start 6, so they are overlapping; and the third end 9 is greater than the fourth start 8 so they are overlapping. So only the first interval is not overlapping. The other intervals are overlapping and merge to an interval starting with 4 and ending with 10.
Solution 1
1 |
|
Explanation 2
-
First, sort the interval by their start time.
-
To form an interval, we need a
start
andend
. Initially, we initializestart
is the first interval’s start time,end
is the first interval’s end time. -
Loop from the second interval to the end, if the iterated interval’s start time is greater than
end
, we know they are disjoint. So we add an interval{start, end}
to the result list. Then we updatestart
be the iterated interval’s start time,end
be the interval’s end time. In the next iteration, if the iterated interva’s start time is less thanend
, we only need to updateend
be the maximum of(end, intervals[i][1])
, we don’t need to updatestart
because we already sortedstart
from small to large, and we only need the minimum start and maximum end.
Solution 2
1 |
|