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.
- Constraints:
1 <= intervals.length <= 10^4,intervals[i].length == 2,0 <= start_i <= end_i <= 10^4 - Example:
# Input
intervals = [[1,3],[2,6],[8,10],[15,18]]
# Output
[[1,6],[8,10],[15,18]]
Solution
Approach
- Sort the intervals based on their starting values to ensure they are evaluated in chronological order.
- Maintain a list (or stack) for merged intervals.
- Iterate through the sorted intervals:
- If the current interval overlaps with the last interval in the merged list (i.e.,
current.start <= last.end), update the end of the last interval to be the maximum of both ends. - Otherwise, append the current interval to the merged list.
- If the current interval overlaps with the last interval in the merged list (i.e.,
Python Code
def merge(intervals):
if not intervals:
return []
intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]
for current in intervals[1:]:
last = merged[-1]
if current[0] <= last[1]:
last[1] = max(last[1], current[1])
else:
merged.append(current)
return merged