Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
OR
Given a list of intervals, merge all the overlapping intervals to produce a list that has only mutually exclusive intervals.
A simple approach is to start from the first interval and compare it with all other intervals for overlapping, if it overlaps with any other interval, then remove the other interval from list and merge the other into the first interval. Repeat the same steps for remaining intervals after first. This approach cannot be implemented in better than O(n^2) time.
Method 2 - Sort on the Basis of Start Time and Merge#
An efficient approach is to first sort the intervals according to start time.
Lets take 3 intervals in sorted array of intervals as a, b and c as interval[i - 1], interval[i] and interval[i+1].
If interval a doesn’t overlap with interval b, then interval c cannot overlap with interval a, because starting time of c must be greater than or equal to b.
Then, we can combine all sorted intervals in a linear traversal.
Following is the detailed step by step algorithm :
Sort the intervals based on increasing order of start time.
Select the first element from the collection of intervals. Lets call it A
For each interval in the collection do the following
If the current interval does not overlap with the A,do nothing.
If the current interval overlaps with A and ending time of current interval is more than that of stack top, update stack top with the ending time of current interval. Put it in new list called result
At the end result collection will contain the merged intervals.
The space complexity of the above algorithm will be O(N) as we need to return a list containing all the merged intervals. We will also need O(N) space for sorting. For Java, depending on its version, Collection.sort() either uses Merge sort or Timsort, and both these algorithms need O(N) space. Overall, our algorithm has a space complexity of O(N).