Merge Intervals
Given a list of intervals, merge all overlapping ones and return the non-overlapping result.
Open on LeetCode ↗Intuition
Sort intervals by start. Then sweep left to right: if the next interval begins before the current merged block ends, they overlap — extend the block's end. Otherwise start a fresh block.
Approach
Pairwise comparison is messy and slow
Comparing every interval against every other for overlap is O(n²), and merging gets tangled because merging two intervals can create a new one that overlaps a third — the merges chain in unpredictable order. We need to impose structure so each interval only ever interacts with one neighbor.
Sort by start, and overlaps become local
Sort the intervals by their start value. Now any interval can only overlap the block immediately before it — never something far behind — because everything earlier started earlier and has already been settled. This collapses the O(n²) tangle into a single left-to-right sweep that compares each interval to just the most recent merged block.
Extend or append, one pass
Seed the result with the first interval. For each subsequent (start, end): if start <= last.end, they overlap, so absorb it by extending last.end = max(last.end, end) (the max matters when one interval fully contains another). Otherwise there's a gap, so start a new block. Using <= makes touching intervals like [1,4] and [4,5] merge. Dominated by the sort: O(n log n) time, O(n) output.
Solution & live demo
Edge cases
start <= last.end is true at equality, so adjacent intervals merge into [1,5].
max(last.end, end) keeps the larger end, so the inner interval is absorbed.
No start <= last.end ever holds, so each interval is appended unchanged.