Merge Intervals
Examples
Example 1:
Input: intervals = [[1,3],[1,5],[6,7]]
Output: [[1,5],[6,7]]
Example 2:
Input: intervals = [[1,2],[2,3]]
Output: [[1,3]]
Example 1:
Input: intervals = [[1,3],[1,5],[6,7]]
Output: [[1,5],[6,7]]
Example 2:
Input: intervals = [[1,2],[2,3]]
Output: [[1,3]]
Given an array of intervals where intervals[i] = [start_i, end_i], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
You may return the answer in any order.
Note: Intervals are non-overlapping if they have no common point. For example, [1, 2] and [3, 4] are non-overlapping, but [1, 2] and [2, 3] are overlapping.
1 <= intervals.length <= 1000intervals[i].length == 20 <= start <= end <= 1000Sort intervals by start time and iterate, merging when the current interval overlaps the last merged interval. If there is no overlap, start a new interval.
Sorting ensures any overlaps must be adjacent in the scan. Merging overlapping intervals into a single interval preserves coverage while maintaining non-overlap among the results.
O(n log n) due to sortingO(n) for the outputclass Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
if not intervals:
return []
intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]
for start, end in intervals[1:]:
last_end = merged[-1][1]
if start <= last_end:
merged[-1][1] = max(last_end, end)
else:
merged.append([start, end])
return merged