Skip to main content

Merge Intervals

Question

Given a collection of intervals, merge all overlapping intervals.

Example 1
None

Solution

all//Merge Intervals.py


def merge_intervals(intervals):
sorted_intervals = sorted(intervals, key = lambda x: x[0])
merged_intervals = []
start, end = sorted_intervals[0]
for i in range(1, len(sorted_intervals)):
current_start, current_end = sorted_intervals[i]
if current_start <= end:
end = max(end, current_end)
else:
merged_intervals.append((start, end))
start, end = current_start, current_end
merged_intervals.append((start, end))
return merged_intervals