The key to solving this problem is to first sort the intervals based on the starting time. Once sorted, we can iterate over the intervals and merge them if they overlap. Two intervals overlap if the start of the current interval is less than or equal to the end of the previous interval.
Time Complexity: O(n log n), due to sorting.
Space Complexity: O(n), required for the output array.
1def merge(intervals):
2 intervals.sort(key=lambda x: x[0])
3 merged = []
4 for interval in intervals:
5 if not merged or merged[-1][1] < interval[0]:
6 merged.append(interval)
7 else:
8 merged[-1][1] = max(merged[-1][1], interval[1])
9 return merged
In Python, the built-in sort
function is used to arrange the intervals. We iterate through and merge the overlapping intervals.
Another approach involves consecutive comparisons and inserting intervals into a new list if they do not overlap with the current interval being processed.
Time Complexity: O(n log n).
Space Complexity: O(n).
1#include <vector>
2#include <algorithm>
3using namespace std;
4
5vector<vector<int>> merge(vector<vector<int>>& intervals) {
6 if (intervals.empty()) return {};
7 sort(intervals.begin(), intervals.end());
8 vector<vector<int>> result = {intervals[0]};
9 for (auto& interval : intervals) {
10 if (result.back()[1] < interval[0]) {
11 result.push_back(interval);
12 } else {
13 result.back()[1] = max(result.back()[1], interval[1]);
14 }
15 }
16 return result;
17}
Here, intervals are sorted, and then directly checked for overlaps while being assigned into a result vector of intervals.