Problem overview
The method merge receives a vector intervals of [start, end] pairs. It merges every group of overlapping intervals and returns the intervals that remain, sorted by start. Intervals overlap when they share at least one point, so intervals that only touch, such as [1,4] and [4,5], merge into [1,5].
For [[1,3],[2,6],[8,10],[15,18]] the answer is [[1,6],[8,10],[15,18]]. The input need not be sorted: [[6,8],[1,9],[2,4],[4,7]] collapses into the single interval [1,9]. The expected time is O(n log n).
Approach: sort so that overlaps are neighbours
In random order, any interval might overlap any other, so you would compare everything with everything. Sorting by start changes that. Once the intervals are in order of start, the ones that overlap come one after another, and each one can only overlap the interval being built right now: the last one in the answer.
So the algorithm keeps a vector merged and looks at the intervals in order. If an interval starts after the last merged interval ends, it begins a new group. Otherwise it overlaps, and the last merged interval grows to cover it. Each interval is looked at once after the sort, so the sort's O(n log n) sets the total time.
On the first example, after sorting (it is already in order), [1,3] starts a group. The interval [2,6] starts at 2, which is not after the last end of 3, so the group becomes [1,6]. Then [8,10] starts after 6 and begins a new group, and so does [15,18]. The answer is [[1,6],[8,10],[15,18]].
Why comparing with the last merged interval alone is enough: the merged intervals are disjoint and in order, and the current interval starts no earlier than any interval before it. If it doesn't reach the last merged interval, it can't reach any earlier one either, because those end even sooner. The answer comes out sorted by start for free, since groups are created in the order the sorted input arrives.
Step by step
- Sort
intervalsby start. Callsortonintervals.begin()andintervals.end()with a lambda that returnsfirst[0] < second[0]. - Declare
merged, avector<vector<int>>for the answer. Its last element is the interval that may still grow. - Loop over
intervalswith a range-basedforandauto&, so that no interval is copied. - Name the two ends:
startisinterval[0]andendisinterval[1]. The next lines then read like the idea. - Start a new group when needed. If
mergedis empty, or the last merged interval ends beforestart, push{start, end}. The comparison is strict (<): an interval that starts exactly where the last one ends touches it, and touching intervals merge. - Otherwise extend the last interval. Set its end to the larger of its current end and
end. Keeping the larger value matters when an interval lies completely inside the last merged one, like[2,3]inside[1,10]. - Return
merged. Every interval went into some merged one, and they are in order of start.
The solution in C++
class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end(), [](auto &first, auto &second) {
return first[0] < second[0];
});
vector<vector<int>> merged;
for (auto& interval : intervals) {
int start = interval[0], end = interval[1];
if (merged.empty() || merged.back()[1] < start) {
merged.push_back({start, end});
} else {
merged.back()[1] = max(merged.back()[1], end);
}
}
return merged;
}
};
For [[6,8],[1,9],[2,4],[4,7]] the sort gives [1,9] [2,4] [4,7] [6,8]. Then [1,9] starts a group, and each of the three others starts at or before 9, so each one is absorbed and the end stays 9. The result is [[1,9]].
The C++ details:
merged.back()returns a reference to the last element, somerged.back()[1] = ...changes the stored interval itself, not a copy.push_back({start, end})builds a newvector<int>from the braces and adds it to the vector.- The empty check comes first. In
merged.empty() || merged.back()[1] < start, the||stops as soon as the left side is true, soback()is never called on an empty vector, where it would be undefined behaviour. - The lambda uses
auto ¶meters (a generic lambda) and a strict<, which is whatsortrequires. The input vector itself is reordered, since the function takes it by non-const reference. auto& intervalis a reference to each element ofintervals. Writingauto intervalwould copy every inner vector.
Complexity
Time: O(n log n). The sort dominates; the merging loop is one pass with constant work per interval.
Space: O(n) for the merged vector in the worst case, when nothing overlaps and every interval is kept. The sort works in place on the input.
Edge cases and common mistakes
- A single interval.
[[5,6]]returns[[5,6]]. - Touching intervals.
[[1,4],[4,5]]returns[[1,5]]. With<=in the condition, the two would stay separate:[[1,4],[4,5]]. - Nothing overlaps.
[[1,2],[3,4]]comes back unchanged. - An interval inside another.
[[1,10],[2,3]]returns[[1,10]]. Setting the end toendwithoutmaxwould shrink the interval to[1,3]. - Skipping the sort. On
[[6,8],[1,9],[2,4],[4,7]]the loop would return[[6,9]]: the interval[1,9]is merged into[6,8], which keeps its later start. - Zero-length intervals. The constraints allow
start == end.[[0,0],[0,0]]returns[[0,0]].
Testing
[[1,3],[2,6],[8,10],[15,18]]gives[[1,6],[8,10],[15,18]].[[1,4],[4,5]]gives[[1,5]].[[6,8],[1,9],[2,4],[4,7]]gives[[1,9]].[[1,10],[2,3]]gives[[1,10]].[[1,2],[3,4]]gives[[1,2],[3,4]].[[0,0],[0,0]]gives[[0,0]].
