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.
1import java.util.ArrayList;
2import java.util.Arrays;
3import java.util.List;
4
5public class Solution {
6 public int[][] merge(int[][] intervals) {
7 if (intervals.length == 0) return new int[0][0];
8 Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
9 List<int[]> merged = new ArrayList<>();
10 for (int[] interval : intervals) {
11 if (merged.isEmpty() || merged.get(merged.size() - 1)[1] < interval[0]) {
12 merged.add(interval);
13 } else {
14 merged.get(merged.size() - 1)[1] = Math.max(merged.get(merged.size() - 1)[1], interval[1]);
15 }
16 }
17 return merged.toArray(new int[merged.size()][]);
18 }
19}
Using Java, the intervals are sorted using Arrays.sort
with a custom comparator. Overlapping intervals are merged by comparing the end of the last interval with the start of the current one.
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.