Start learning free

LESSON 268 OF 314 · INTERVALS

Merge Intervals in C++: Sort by Start, Then One Pass, O(n log n)

Practice O(n log n) Read the full explanation

You get a vector of intervals. Each interval is a pair [starti, endi]. It covers every point from its start to its end.

Merge the intervals that overlap. Return a vector of the intervals you end up with, sorted by start.

Two intervals overlap if they share at least one point. Intervals that only touch count too. For example, [2,5] and [5,6] share the point 5. They become [2,6].

 

Example 1:

Input: intervals = [[5,8],[1,3],[7,11],[13,14]]
Output: [[1,3],[5,11],[13,14]]
Explanation: The input is not sorted.
[5,8] and [7,11] share 7 and 8.
They become [5,11].
[1,3] and [13,14] overlap no other interval.

Example 2:

Input: intervals = [[2,5],[5,6],[9,9]]
Output: [[2,6],[9,9]]
Explanation: [2,5] and [5,6] touch at 5.
That is enough to merge them.
[9,9] is a single point.
It stays on its own.

Example 3:

Input: intervals = [[3,20],[4,6],[10,12]]
Output: [[3,20]]
Explanation: [4,6] and [10,12] lie inside [3,20].
All three merge into [3,20].
It ends at 20, not at 12.

 

Constraints:

  • 1 to 100,000 intervals, in any order.
  • Each start and end is a whole number from 0 to 1,000,000.
  • No start is greater than its end.

Note:

Your algorithm should run in O(n log n) time, where n is the number of intervals.

STEP 1 OF 7
    Ctrl + Enter to check

    C++ · INTERVALS

    Merge Intervals in C++, explained

    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

    1. Sort intervals by start. Call sort on intervals.begin() and intervals.end() with a lambda that returns first[0] < second[0].
    2. Declare merged, a vector<vector<int>> for the answer. Its last element is the interval that may still grow.
    3. Loop over intervals with a range-based for and auto&, so that no interval is copied.
    4. Name the two ends: start is interval[0] and end is interval[1]. The next lines then read like the idea.
    5. Start a new group when needed. If merged is empty, or the last merged interval ends before start, push {start, end}. The comparison is strict (<): an interval that starts exactly where the last one ends touches it, and touching intervals merge.
    6. 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].
    7. 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, so merged.back()[1] = ... changes the stored interval itself, not a copy.
    • push_back({start, end}) builds a new vector<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, so back() is never called on an empty vector, where it would be undefined behaviour.
    • The lambda uses auto & parameters (a generic lambda) and a strict <, which is what sort requires. The input vector itself is reordered, since the function takes it by non-const reference.
    • auto& interval is a reference to each element of intervals. Writing auto interval would 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 to end without max would 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]].
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free