Merge Intervals
Medium
Topics
Given an array of intervals (each [start, end]), merge all overlapping intervals and return the non-overlapping result sorted by start. On this judge intervals are shown separated by |.
Example 1
Two intervals merge when they touch or overlap, which on this axis means their bars line up vertically. Sorting by start is what makes that a single pass: every interval either extends the one being built or starts a new one. 4 in, 3 out.
Each lane is one interval drawn on a shared axis, so overlaps line up vertically.
Input: grid = [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]]
Example 2
Input: grid = [[1,4],[4,5]] Output: [[1,5]]
Constraints
- 1 <= intervals.length <= 10^4
- intervals[i].length == 2
Editorial — intuition, approach, complexity and pitfalls
Intuition
Once sorted by start, overlapping intervals are adjacent. Walk through and extend the current merged interval whenever the next one starts before the current end.
Approach
- Sort intervals by start.
- Keep a running merged interval; if the next starts within it, extend the end to the max.
- Otherwise push the current and start a new one.
Dry Run
intervals = [1,3] [2,6] [8,10] [15,18] (already in start order)
[1,3] nothing merged yet -> open a new interval [1,3]
[2,6] starts at 2, current end is 3 -> 2 <= 3, extend to [1,6]
[8,10] starts at 8, current end is 6 -> 8 > 6, open [8,10]
[15,18] starts at 15, current end is 10 -> open [15,18]
answer [1,6] [8,10] [15,18]
Taking max(current end, e) rather than just e is the detail that matters, because
the next interval can be entirely INSIDE the current one. On [[1,5],[2,3],[4,8]]
the correct answer is [[1,8]], but a plain assignment gives [[1,3],[4,8]]: the
[1,5] is truncated to [1,3], and then [4,8] no longer looks like an overlap at
all. One wrong assignment produces two wrong intervals.
The comparison is <=, which is the opposite of meeting-rooms where it is strict.
Both are right for their own question. Here touching intervals should merge --
[1,4] and [4,5] become [1,5] -- because the task is covering a range. There,
touching meetings are compatible, because the task is occupying a room.
Sorting is what makes a single backward glance sufficient: after it, anything
that overlaps the interval being built must start at or before its end, so the
only candidate is the immediately previous merged interval.Complexity
- Time — O(n log n): sort plus a linear merge.
- Space — O(n): the output list.
Common Pitfalls
- Extend using max of ends — the next interval may be fully inside the current one.
Full Solution — all languages
class Solution:
def merge(self, grid):
intervals=grid; intervals.sort()
res=[]
for s,e in intervals:
if res and s<=res[-1][1]:
res[-1][1]=max(res[-1][1],e)
else:
res.append([s,e])
return resimport java.util.*;
class Solution {
public int[][] merge(int[][] grid) {
Arrays.sort(grid,(a,b)->a[0]!=b[0]?a[0]-b[0]:a[1]-b[1]);
List<int[]> res=new ArrayList<>();
for(int[] iv:grid) {
if(!res.isEmpty()&&iv[0]<=res.get(res.size()-1)[1])res.get(res.size()-1)[1]=Math.max(res.get(res.size()-1)[1],iv[1]);
else res.add(new int[]{iv[0],iv[1]});
}
return res.toArray(new int[0][]);
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<vector<int>> merge(vector<vector<int>>& grid) {
sort(grid.begin(),grid.end());
vector<vector<int>> res;
for(auto& iv:grid) {
if(!res.empty()&&iv[0]<=res.back()[1])res.back()[1]=max(res.back()[1],iv[1]);
else res.push_back(iv);
}
return res;
}
};/**
* @param {number[][]} grid
* @return {number[][]}
*/ var merge = function(grid) {
grid.sort((a,b)=>a[0]-b[0]||a[1]-b[1]);
const res=[];
for(const iv of grid) {
if(res.length&&iv[0]<=res[res.length-1][1])res[res.length-1][1]=Math.max(res[res.length-1][1],iv[1]);
else res.push([iv[0],iv[1]]);
}
return res;
};