Q&A-4What does merging overlapping intervals guarantee, and what does it deliberately leave open?
Answer
The guarantee. Merging overlapping intervals returns a canonical form: the intervals come out sorted by start, pairwise disjoint, and their union equals the union of the input. It is also minimal, no two output intervals can be combined without changing the union, and idempotent: merging the result again returns it unchanged. That is the whole contract. Everything else is a choice the merge does not make for you.
Why minimal and unique. For closed intervals the union of any family is itself a union of maximal intervals, and that decomposition is unique. Merging just computes it. The mechanism is one left-to-right pass over the input sorted by start: hold the current interval, and when the next one starts at or before the current end, extend the current end to the larger of the two; otherwise emit and start fresh.
def merge(intervals): # closed intervals [s, e], s <= e
out = []
for s, e in sorted(intervals):
if out and s <= out[-1][1]:
out[-1][1] = max(out[-1][1], e)
else:
out.append([s, e])
return outTrace on [(1,10),(2,3),(5,12),(20,21)]:
| step | interval | out before | action |
|---|---|---|---|
| 1 | (1,10) | [] | append → [[1,10]] |
| 2 | (2,3) | [[1,10]] | 2 ≤ 10, end = max(10,3) = 10 → [[1,10]] |
| 3 | (5,12) | [[1,10]] | 5 ≤ 10, end = max(10,12) = 12 → [[1,12]] |
| 4 | (20,21) | [[1,12]] | 20 > 12, append → [[1,12],[20,21]] |
Result [[1,12],[20,21]]. Feeding that back in returns the same list: idempotence.
What it leaves open.
- Boundary convention. Whether touching intervals merge is not decided by the merge; it is decided by whether your intervals are closed or half-open.
[1,2]and[2,3]share the point 2 and merge to[1,3];[1,2)and[2,3)do not touch and stay separate. The only change iss <= out[-1][1]versuss < out[-1][1]. Pick the one that matches your data and say which. - Provenance. A merged interval does not record which inputs produced it. If you need to map back (which meetings, which IP ranges, which orders) carry a payload list alongside the bounds.
- Output order. Sorted by start is a choice, not a consequence of merging. If a caller needs input order, you must restore it.
- Cost. The guarantee is about the result, not the algorithm. Sorting dominates at O(n log n); a sweep over already-sorted input is O(n).
Failure modes. Using < on closed intervals leaves exactly-touching intervals unmerged: a zero-width gap that is really a shared point; a test with [1,2],[2,3] catches it. Assigning e instead of max(out[-1][1], e) shrinks the range under containment: [(1,10),(2,3)] becomes [(1,3)], silently dropping (3,10]. Skipping the sort misses merges that only appear once the input is ordered.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.