Optimization · Intermediate

Sort and merge intervals

Sort intervals by start, then sweep once: each interval either extends the current merged block or starts a new one.

On this page
  1. The idea
  2. How to recognise it
  3. When not to use it
  4. Template
  5. Complexity
  6. Worked examples
  7. Pitfalls
  8. Practise it
  9. Learn the foundations
  10. References

The idea

Overlap questions are hard on unsorted intervals because any pair might overlap. After sorting by start, an interval can only overlap the block that is currently open: everything earlier ended before the current block began or was absorbed into it.

The same sweep answers related questions: insert one interval into a sorted list, find gaps (free time), and with a min-heap of end times, count how many intervals overlap at once (rooms needed).

How to recognise it

  • Input is a list of [start, end] pairs: meetings, bookings, ranges, segments.
  • Questions about overlap, union, total covered length, free slots or maximum concurrency.
  • Order of the input does not matter for the answer.

When not to use it

  • Intervals are inserted and queried online in large numbers: an interval tree or ordered map avoids re-sorting.
  • The coordinates are small integers and you need coverage counts: a difference array over the coordinate range is simpler.

Template

Language-neutral pseudocode (Python-like). Adapt names and types to your language; the solved problems below have tested implementations in C#, Python, Java and C++.

sort intervals by start
merged = []
for (s, e) in intervals:
    if merged and s <= merged.last().end:     # overlaps (or touches) the open block
        merged.last().end = max(merged.last().end, e)
    else:
        merged.push((s, e))
return merged
  • Decide whether touching intervals ([1, 3] and [3, 5]) count as overlapping; it is the `<=` versus `<` in the condition.
  • Take the max of the ends: a later-starting interval can end earlier than the open block.

Complexity

Time O(n log n), extra space O(n). Sorting dominates; the sweep is linear. Output space is O(n) in the worst case (no overlaps).

Worked examples

Merging [1,4], [2,3], [6,8], [7,9]

Sorted already. [1,4] opens a block. [2,3] starts inside it; end stays max(4, 3) = 4. [6,8] starts after 4: new block. [7,9] extends it to 9. Result [1,4], [6,9].

Pitfalls

  • Overwriting the end with the new interval's end instead of the maximum.
  • Sorting by end when the sweep assumes sorting by start (the greedy scheduling problem is the one that sorts by end).

Practise it

Solved problems with hints, a correctness argument and four tested implementations:

Learn the foundations

Related patterns

References

dsa.pattern.merge-intervals · version 1