PythiloMedium · 20 min · Task 8 of 20 · progress kept in this browser

Merge intervals

You are given ranges of time as (start, end) pairs, in any order. Combine all that overlap so the result covers the same time with the fewest ranges.

merge_intervals([(5, 7), (1, 3), (2, 4)])
# [(1, 4), (5, 7)]
merge_intervals([(1, 3), (3, 5)])
# [(1, 5)]

Touching pairs count as overlapping, as the second example shows.

Your task

Write merge_intervals(intervals) returning a sorted list of merged (start, end) tuples, merging overlapping and touching pairs, without changing the input.