To merge overlapping intervals, we can follow these steps:
-
Sort the Intervals: First, sort the intervals based on their start times. This allows us to process each interval in order and easily determine if the current interval overlaps with the previous one.
-
Initialize a Merged List: Start with the first interval in the merged list.
-
Iterate and Merge: For each subsequent interval, compare its start time with the end time of the last interval in the merged list:
- If the current interval's start time is less than or equal to the end time of the last merged interval, it means they overlap. Merge them by updating the end time of the last merged interval to be the maximum of the two end times.
- If they do not overlap, simply add the current interval to the merged list.
Here’s the implementation in Python:
def merge_intervals(intervals):
if not intervals:
return []
# Sort intervals based on the start time
intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]
for current in intervals[1:]:
last = merged[-1]
if current[0] <= last[1]:
# Overlapping intervals, merge them
merged[-1] = [last[0], max(last[1], current[1])]
else:
merged.append(current)
return merged
# Example usage:
intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]
print(merge_intervals(intervals)) # Output: [[1, 6], [8, 10], [15, 18]]
Explanation:
- Sorting: The intervals are sorted by their start times to ensure we process them in chronological order.
- Initialization: The
merged list starts with the first interval from the sorted list.
- Merging Process:
- For each subsequent interval, we check if it overlaps with the last interval in the
merged list.
- If it overlaps (
current[0] <= last[1]), we merge them by extending the end of the last interval in merged to the maximum end of the two intervals.
- If it does not overlap, we add the current interval to
merged.
Time Complexity:
- Sorting: (O(n \log n)), where (n) is the number of intervals.
- Merging: (O(n)), as we process each interval once.
- Overall: (O(n \log n)), dominated by the sorting step.
Space Complexity:
- (O(n)) for storing the merged intervals, where (n) is the number of intervals.
This approach efficiently merges all overlapping intervals while maintaining the order and ensuring no overlaps in the final result.