Merge overlapping intervals
Sort by start. After that an interval can only overlap the one immediately before it, so a single pass merges everything: extend the last kept interval if it reaches this one, otherwise start a new one. O(n log n) for the sort, O(n) after it.
Overview
Why sorting collapses the problem
Unsorted, any interval can overlap any other, so you are looking at pairs — O(n²). Sorted by start, an interval's only possible overlap is with the merged block immediately behind it, because everything earlier starts earlier and has already been absorbed.
That reduces the whole thing to one comparison per interval. The sort costs O(n log n) and dominates.
Step through it
What to watch
- Sorting is the whole trick — without it every pair must be compared.
- Only the last merged interval is ever checked.
- Extending takes the larger end, not this interval's end.
Say this out loud
"Sort by start, then sweep. Each interval either extends the last merged one or starts a new one. The sort dominates, so O(n log n)."