Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Merge Intervals

Hard · 80 XP

Merge overlapping intervals and print each surviving interval as start-end, one per line.

Target output
1-6
8-12
15-18
Blank · autosaved
PYmerge-intervals.py
Run your code to check it…
Guide

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

  1. Sorted: (1, 3), (2, 6), (8, 10), (9, 12), (15, 18). Start with [1, 3].
  2. (2, 6) starts at 2, which is ≤ 3: extend to [1, 6]. (8, 10) starts after 6, so start a new interval [8, 10].
  3. (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.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path