Merge Intervals
Medium · Intervals
Jump to codeMerge all overlapping closed intervals from an unsorted list and return a list sorted by start. Intervals touching at an endpoint should merge.
Examples
Example 1
intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Example 2
intervals = [[1,4],[4,5]]
Output: [[1,5]]
Constraints
- 1 <= intervals.length <= 1000
- intervals[i].length == 2
- 0 <= start <= end <= 1000
Need a hint?
Sorting makes every possible overlap adjacent to the current merged interval.
Asked in real interviews
Candidates reported versions of Merge Intervals from these company interviews. Some company questions are locked and open with Premium or XP.
- Merge Overlapping Intervals with a SweepAmazon
- Merge intervals and design rating APIsAtlassian
- Merge overlapping intervalsOpenAI
Solution approach
Sort by start. Keep a current merged interval. If the next start is at most its end, extend the end to the maximum of both ends. Otherwise emit the current interval and start a new one. Emit the final interval; empty input yields empty output.
Complexity
O(n log n) time and O(n) result space.
Python reference solution
def merge(intervals):
answer = []
for start, end in sorted(intervals):
if answer and start <= answer[-1][1]:
answer[-1][1] = max(answer[-1][1], end)
else:
answer.append([start, end])
return answer
JavaScript solution
function merge(intervals) {
intervals.sort((a, b) => a[0] - b[0]);
const answer = [];
for (const [start, end] of intervals) {
if (answer.length && start <= answer[answer.length - 1][1]) {
answer[answer.length - 1][1] = Math.max(answer[answer.length - 1][1], end);
} else answer.push([start, end]);
}
return answer;
}
Java solution
import java.util.*;
class Solution {
public int[][] merge(int[][] intervals) {
Arrays.sort(intervals, Comparator.comparingInt(interval -> interval[0]));
List<int[]> answer = new ArrayList<>();
for (int[] interval : intervals) {
if (!answer.isEmpty() && interval[0] <= answer.get(answer.size() - 1)[1]) {
int[] last = answer.get(answer.size() - 1);
last[1] = Math.max(last[1], interval[1]);
} else answer.add(interval.clone());
}
return answer.toArray(new int[0][]);
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<int>> merge(vector<vector<int>> &intervals) {
sort(intervals.begin(), intervals.end());
vector<vector<int>> answer;
for (auto& interval : intervals) {
if (!answer.empty() && interval[0] <= answer.back()[1]) {
answer.back()[1] = max(answer.back()[1], interval[1]);
} else answer.push_back(interval);
}
return answer;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 9 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
[
1,
3
],
[
2,
6
],
[
8,
10
],
[
15,
18
]
]
][
[
1,
6
],
[
8,
10
],
[
15,
18
]
][
[
[
1,
4
],
[
4,
5
]
]
][
[
1,
5
]
][
[
[
1,
2
],
[
3,
4
]
]
][
[
1,
2
],
[
3,
4
]
][
[
[
1,
10
],
[
2,
3
],
[
4,
5
]
]
][
[
1,
10
]
][
[
[
5,
6
],
[
1,
4
]
]
][
[
1,
4
],
[
5,
6
]
]Drafts are saved per language in this browser when storage is available.