Merge Intervals
Calendar apps, memory allocators, and half of all interview loops run on this: sort intervals by start, then sweep once, growing or closing the current merged block. The classic that punishes off-by-one thinking at the boundaries.
The problem
Given intervals, a list of [start, end] pairs (start ≤ end, any order), merge all overlapping intervals and return the result sorted by start. Two intervals overlap if one starts before or exactly when the other ends — touching intervals like [1,4] and [4,5] merge into [1,5].
intervals = [[1,3],[2,6],[8,10],[15,18]][[1,6],[8,10],[15,18]]intervals = [[1,4],[4,5]][[1,5]]intervals = [[1,10],[2,3]][[1,10]]- Input may be unsorted — sort by start first.
- Touching counts as overlapping: next.start ≤ current.end merges.
- Merging takes max(end) — nested intervals must not shrink the block.
Your turn — write it
Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are right above and Reveal solution is one click away.
Implement merge_intervals(intervals) → the minimal list of non-overlapping intervals covering the input, sorted by start.
- Sort by start. After that, only the CURRENT merged block can ever absorb the next interval.
- If next.start ≤ current.end, extend: current.end = max(current.end, next.end).
- Otherwise close the block, append it, and start a new one.
- The nested case [[1,10],[2,3]] is why the max() matters.
Explore the topic
See this challenge alongside everything else on the same subject — handbooks, system designs, algorithms and tools, in one place.