Back to solutions
Merge Intervals
MediumArraysMerge all overlapping intervals.
Constraints
- 1 <= n <= 10^4
- start <= end
Sort then sweep
Time O(n log n)Space O(n)
Sort the intervals by start. Walk through them keeping the last merged interval; if the current interval starts at or before the last one's end, they overlap, so extend the last end. Otherwise the current interval begins a new block.
Key terms
- interval:
- A [start, end] range on the number line.
- overlap:
- Two intervals overlap when one starts at or before the other ends.
vector<vector<int>> merge(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end());
vector<vector<int>> res;
for (auto& iv : intervals) {
if (!res.empty() && iv[0] <= res.back()[1])
res.back()[1] = max(res.back()[1], iv[1]);
else res.push_back(iv);
}
return res;
}Step by step
- Sort intervals by their start value.
- Start the result with the first interval.
- For each next interval, if its start <= the last result's end, extend that end to the max of the two.
- Otherwise append it as a new interval. Return the result list.