56. Merge Intervals
Medium NeetCode 150 ↗ Open on LeetCode Source: Standard solution only
Quick review
- Pattern
- Intervals
- Time
- O(n log n)
- Space
- O(n)
Standard Solution (C++)
SummaryCombine all overlapping intervals in a list and return the resulting non-overlapping set.
Approach
Key idea: After sorting by start, overlapping intervals are adjacent, so a single pass can merge them.
Steps:
- Sort intervals by start time.
- Keep a running merged interval; if the next interval starts at or before its end, extend the end.
- Otherwise push the running interval and start a new one.
class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end());
vector<vector<int>> result;
for (auto& iv : intervals) {
if (!result.empty() && iv[0] <= result.back()[1]) {
result.back()[1] = max(result.back()[1], iv[1]);
} else {
result.push_back(iv);
}
}
return result;
}
}; Time O(n log n) Space O(n)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.