Merge Intervals
Difficulty: Medium · Pattern: Intervals · LeetCode #56
Merge all overlapping intervals and return the resulting non-overlapping intervals sorted by start. Intervals that touch (one ends exactly where the next starts) also merge.
Examples
text
[[1, 4], [8, 10], [3, 6], [15, 18]] → [[1, 6], [8, 10], [15, 18]]
[[1, 4], [4, 5]] → [[1, 5]]
[[5, 7]] → [[5, 7]]Hints
- Unsorted input hides overlaps. Sort by start time first.
- After sorting, an interval either overlaps the last merged interval or starts a new one.
Approach
Sort by start. Keep a result list; for each interval, if its start ≤ the end of the last merged interval, extend that end to max(lastEnd, end) (the new interval might be fully contained). Otherwise append it as a new interval. O(n log n) for the sort plus O(n) to sweep.
Complexity
Time: O(n log n). Space: O(n) for the output.
Python solution
def merge(intervals):
intervals.sort(key=lambda x: x[0])
out = []
for s, e in intervals:
if out and s <= out[-1][1]:
out[-1][1] = max(out[-1][1], e)
else:
out.append([s, e])
return outJavaScript solution
function merge(intervals) {
intervals.sort((a, b) => a[0] - b[0]);
const out = [];
for (const [s, e] of intervals) {
if (out.length && s <= out[out.length - 1][1]) out[out.length - 1][1] = Math.max(out[out.length - 1][1], e);
else out.push([s, e]);
}
return out;
}