Merge Intervals
Merge Intervals is a medium intervals problem solved with the basics pattern.
The best approach, optimal (sort, then one sweep), runs in O(n log n) time and O(n) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from repeated pairwise merging up.
Problem
Given a collection of intervals, merge all overlapping intervals and return the non-overlapping intervals that cover exactly the same ranges.
Examples
Example 1
- Input
intervals = [[1, 3], [8, 10], [2, 6], [15, 18]]- Output
[[1, 6], [8, 10], [15, 18]]
Example 2
- Input
intervals = [[1, 4], [4, 5]]- Output
[[1, 5]]- Why
- Touching intervals merge.
Constraints
1 <= intervals.length <= 10^4; closed intervals.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 10 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Repeated pairwise merging | O(n³) | O(n) |
| Optimal (sort, then one sweep) | O(n log n) | O(n) |
1Repeated pairwise merging
O(n³)Up to n merge rounds, each scanning O(n²) pairs.O(n)Keep merging any two overlapping intervals until no pair overlaps.
- Loop: find any overlapping pair, replace it with its union, repeat.
class Solution {
public int[][] merge(int[][] intervals) {
List<int[]> list = new ArrayList<>(Arrays.asList(intervals));
boolean changed = true;
while (changed) {
changed = false;
outer:
for (int i = 0; i < list.size(); i++)
for (int j = i + 1; j < list.size(); j++) {
int[] a = list.get(i), b = list.get(j);
if (Math.max(a[0], b[0]) <= Math.min(a[1], b[1])) {
list.set(i, new int[] { Math.min(a[0], b[0]), Math.max(a[1], b[1]) });
list.remove(j);
changed = true;
break outer;
}
}
}
list.sort((x, y) -> Integer.compare(x[0], y[0]));
return list.toArray(new int[0][]);
}
}class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
lst = list(intervals)
changed = True
while changed:
changed = False
for i in range(len(lst)):
for j in range(i + 1, len(lst)):
a, b = lst[i], lst[j]
if max(a[0], b[0]) <= min(a[1], b[1]):
lst[i] = [min(a[0], b[0]), max(a[1], b[1])]
del lst[j]
changed = True
break
if changed:
break
lst.sort(key=lambda x: x[0])
return lstclass Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
vector<vector<int>> list(intervals.begin(), intervals.end());
bool changed = true;
while (changed) {
changed = false;
for (int i = 0; i < (int)list.size() && !changed; i++)
for (int j = i + 1; j < (int)list.size(); j++) {
vector<int> a = list[i], b = list[j];
if (max(a[0], b[0]) <= min(a[1], b[1])) {
list[i] = {min(a[0], b[0]), max(a[1], b[1])};
list.erase(list.begin() + j);
changed = true;
break;
}
}
}
stable_sort(list.begin(), list.end(), [](const vector<int>& x, const vector<int>& y) { return x[0] < y[0]; });
return list;
}
};function merge(intervals) {
const list = [...intervals];
let changed = true;
while (changed) {
changed = false;
outer:
for (let i = 0; i < list.length; i++)
for (let j = i + 1; j < list.length; j++) {
const a = list[i], b = list[j];
if (Math.max(a[0], b[0]) <= Math.min(a[1], b[1])) {
list[i] = [Math.min(a[0], b[0]), Math.max(a[1], b[1])];
list.splice(j, 1);
changed = true;
break outer;
}
}
}
list.sort((x, y) => x[0] - y[0]);
return list;
}2Optimal (sort, then one sweep)
O(n log n)O(n)After sorting by start, compare each interval with the last merged one. If it starts at or before that interval's end, extend the end with max; otherwise start a new merged interval.
- Sort by start.
- If out is empty or cur.start > last.end, append cur.
- Else last.end = max(last.end, cur.end).
class Solution {
public int[][] merge(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
List<int[]> out = new ArrayList<>();
for (int[] cur : intervals) {
if (out.isEmpty() || cur[0] > out.get(out.size() - 1)[1]) out.add(new int[] { cur[0], cur[1] });
else {
int[] last = out.get(out.size() - 1);
last[1] = Math.max(last[1], cur[1]);
}
}
return out.toArray(new int[0][]);
}
}class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals.sort(key=lambda a: a[0])
out = []
for cur in intervals:
if not out or cur[0] > out[-1][1]:
out.append([cur[0], cur[1]])
else:
last = out[-1]
last[1] = max(last[1], cur[1])
return outclass Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end(), [](const vector<int>& a, const vector<int>& b) { return a[0] < b[0]; });
vector<vector<int>> out;
for (auto& cur : intervals) {
if (out.empty() || cur[0] > out.back()[1]) out.push_back({cur[0], cur[1]});
else {
vector<int>& last = out.back();
last[1] = max(last[1], cur[1]);
}
}
return out;
}
};function merge(intervals) {
intervals.sort((a, b) => a[0] - b[0]);
const out = [];
for (const cur of intervals) {
if (out.length === 0 || cur[0] > out[out.length - 1][1]) out.push([cur[0], cur[1]]);
else {
const last = out[out.length - 1];
last[1] = Math.max(last[1], cur[1]);
}
}
return out;
}Edge cases to test
- Unsorted input
- One interval swallowing several others
- Touching endpoints
Hints
Hint 1
Sort by start. Then each interval either extends the last merged interval or starts a new one.
FAQ
What is the best time complexity for Merge Intervals?
Optimal (sort, then one sweep) runs in O(n log n) time and O(n) extra space.
Which pattern does Merge Intervals use?
It is a intervals problem that uses the basics pattern. Other problems with the same pattern: Detect overlap unsorted, Detect overlap sorted intervals, Interval List Intersections.
Is there a brute force solution for Merge Intervals?
Yes. Repeated pairwise merging takes O(n³) time and O(n) space. Keep merging any two overlapping intervals until no pair overlaps.
Which edge cases should I test for Merge Intervals?
Unsorted input; One interval swallowing several others; Touching endpoints.