Merge Intervals
Hard · 80 XPMerge overlapping intervals and print each surviving interval as start-end, one per line.
1-6 8-12 15-18
Sort by start. If the next interval starts at or before the current end, extend the end to the max of the two.
intervals = [(1, 3), (8, 10), (2, 6), (15, 18), (9, 12)]
merged = []
for start, end in sorted(intervals):
if merged and start <= merged[-1][1]:
merged[-1][1] = max(merged[-1][1], end)
else:
merged.append([start, end])
for start, end in merged:
print(f"{start}-{end}")
Run your code to check it…
How to approach Merge Intervals
Overlapping intervals are only easy to spot once they are in order, so sort by start time first. After that, any interval that overlaps the current merged one must come right after it.
Walk the sorted list keeping a merged list. If the next interval starts at or before the end of the last merged interval, they overlap: extend that end to the larger of the two ends. Otherwise, start a new merged interval. Store them as lists rather than tuples so the end can be updated in place.
Worked through on this data
- Sorted: (1, 3), (2, 6), (8, 10), (9, 12), (15, 18). Start with [1, 3].
- (2, 6) starts at 2, which is ≤ 3: extend to [1, 6]. (8, 10) starts after 6, so start a new interval [8, 10].
- (9, 12) overlaps it: extend to [8, 12]. (15, 18) starts fresh. Output: 1-6, 8-12, 15-18.
Common mistakes
- Skipping the sort: (8, 10) comes before (2, 6) in the input, so the merge misses overlaps.
- Setting the end to the new interval's end instead of the maximum: merging (1, 10) with (2, 3) would shrink it to (1, 3).
- Tuples cannot be modified, so
merged[-1][1] = ...raises a TypeError if you stored tuples.
Time and space
Sorting dominates at O(n log n); the merge pass itself is O(n). The output takes O(n) space in the worst case.
Where this shows up
Calendar apps merge busy slots to find free time, and the same pass consolidates IP address ranges, video watch segments and booking overlaps.
Take it further
Given a list of meetings, find the free gaps between 9 and 17, using the merged intervals as the busy times.