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.
Example 1:
Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
Example 2:
Input: intervals = [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considered overlapping.
Constraints:
1 <= intervals.length <= 104
intervals[i].length == 2
0 <= starti <= endi <= 104
The problem asks to merge overlapping intervals. The most efficient approach uses sorting and a single pass.
Algorithm:
Sort: Sort the intervals based on their start times. This is crucial for efficiently identifying overlapping intervals. We can use any efficient sorting algorithm; the built-in sort functions in most languages have a time complexity of O(n log n).
Merge: Iterate through the sorted intervals. Maintain a variable to track the last merged interval.
Return: After processing all intervals, return the result list containing the merged non-overlapping intervals.
Time Complexity Analysis:
Space Complexity Analysis:
Code Examples (with comments):
Python:
def merge(intervals):
# Sort intervals by start time
intervals.sort()
merged = []
for interval in intervals:
# If the list of merged intervals is empty or if the current interval does not overlap with the last merged interval
if not merged or interval[0] > merged[-1][1]:
merged.append(interval) # Add the current interval as a new merged interval
else:
# Merge the current interval with the last merged interval
merged[-1][1] = max(merged[-1][1], interval[1])
return merged
Java:
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
class Solution {
public int[][] merge(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> a[0] - b[0]); // Sort by start time
List<int[]> merged = new ArrayList<>();
for (int[] interval : intervals) {
if (merged.isEmpty() || interval[0] > merged.get(merged.size() - 1)[1]) {
merged.add(interval);
} else {
merged.get(merged.size() - 1)[1] = Math.max(merged.get(merged.size() - 1)[1], interval[1]);
}
}
return merged.toArray(new int[0][]); // Convert List to int[][]
}
}
The other languages (C++, JavaScript, Go, etc.) would follow a very similar structure, with minor syntax differences. The core logic of sorting and iterating to merge remains the same.