Merge Intervals

Merge overlapping intervals — sort by start, then sweep linearly.

Medium
Time O(n log n) Space O(n)
LeetCode
3 min read
intervals sorting

Problem#

Given a collection of intervals [start, end], merge all overlapping intervals and return the resulting non-overlapping list.

Examples#

  • [[1,3],[2,6],[8,10],[15,18]][[1,6],[8,10],[15,18]]
  • [[1,4],[4,5]][[1,5]] (touching counts as overlapping)

Constraints#

  • 1 <= intervals.length <= 10^4.

Approach#

Sort by start. Walk through; if the current interval’s start ≤ the last merged interval’s end, extend the last; else push the current.

Solution#

Merge Intervals
class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end());
vector<vector<int>> ans;
for (auto& it : intervals) {
if (!ans.empty() && it[0] <= ans.back()[1]) {
ans.back()[1] = max(ans.back()[1], it[1]);
} else {
ans.push_back(it);
}
}
return ans;
}
};

Editorial#

Sorting by start lets us decide overlap with a one-shot comparison against the last merged interval — anything else in the sorted order will start no earlier. The max(end) accounts for fully-nested intervals (current is entirely inside the previous, end shouldn’t shrink).

Complexity#

  • Time: O(n log n).
  • Space: O(n) for output.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.