medium

Merge Intervals

Given a collection of closed intervals, merge every group of overlapping intervals and return the resulting non-overlapping intervals that cover the same points.

Constraints
  • 1 ≤ intervals.length ≤ 10^4
  • 0 ≤ start ≤ end ≤ 10^4
Examples
in: intervals = [[1,3],[2,6],[8,10],[15,18]]
out: [[1,6],[8,10],[15,18]]
Recognition clues
  • Intervals with overlap
  • After sorting by start, an overlap can only be with the last merged interval
  • Single linear pass after sorting
Pattern
Intervals

Sort by start (or end) time and sweep: two intervals overlap iff the next start is before the current end, and after sorting each interval only needs comparing with the one being built. Counting concurrent intervals is a sweep over sorted endpoints, or a min-heap of end times.

Solution

Sort by start. Walk through the intervals keeping the last interval of the output. If the current start is ≤ the last end, extend the last end to the max of the two ends; otherwise append the current interval as a new entry. Sorting guarantees that any interval overlapping an earlier one overlaps the most recently merged block.

time O(n log n)space O(n)
Alternative approaches
  • Without sorting you would need repeated O(n^2) pair merging. An interval tree supports dynamic insertions with merge queries.
Code it yourself
Solve in
Hints: