Merge Intervals

Pattern: Intervals

medium

Sort by start. Then walk once, keeping the last merged interval. A new interval that starts by its end stretches it; anything else starts a new one.

The problem

You are given a list of intervals [start, end] in any order. Merge every group of overlapping intervals into one, and return the merged intervals. Intervals that share an end point overlap, so [1, 4] and [4, 5] become [1, 5]. For example, [[1, 3], [2, 6], [8, 10], [15, 18]] gives [[1, 6], [8, 10], [15, 18]].

The function name merge matches LeetCode. Use the link above for the exact statement and limits. LeetCode accepts the answer in any order. This guide returns it sorted by start, which the method gives anyway.

Think first

  • If the intervals were sorted by start, which earlier interval could a new one overlap?
  • When two overlap, what is the merged end?
  • Is [1, 4] with [2, 3] handled by your rule?

Hints

    Brute force, and why it fails

    Compare every pair, merge any two that overlap, and repeat until nothing changes: O(n²) or worse. This guide checks its tests a different way, by marking every covered point on a number line and reading the covered runs back. Sorting first is O(n log n).

    The key insight

    After sorting by start, an interval can only overlap the merged interval just before it. Every older merged interval already ended before that one began.

    Dry run

    [8, 10]0 
    [1, 3]1 
    [15, 18]2 
    [2, 6]3 

    intervals are [8, 10], [1, 3], [15, 18] and [2, 6]. Sort them by start first.

    Step 1 of 4

    The plan

    sort intervals by start
    out = empty list
    for each [s, e] in intervals:
        if out is not empty and s <= last end in out:
            last end in out = max(last end in out, e)
        else:
            add [s, e] to out
    return out
    

    Complexity

    Time
    O(n log n)
    Space
    O(n)

    The sort costs O(n log n) and the walk O(n). The output takes up to n intervals, and the sort may use O(log n) to O(n) memory depending on the language.

    Edge cases

    • One interval: returned as it is.
    • Touching intervals, [1, 4] and [4, 5]: merged to [1, 5].
    • One interval inside another, [1, 4] and [2, 3]: stays [1, 4], because the end is the larger one.
    • Input not sorted, as in [[4, 7], [1, 4]]: sorting first is what makes it [[1, 7]].
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int[][] merge(int[][] intervals) {
            Arrays.sort(intervals, (x, y) -> Integer.compare(x[0], y[0]));   // by start
            List<int[]> out = new ArrayList<>();
            for (int[] cur : intervals) {
                if (!out.isEmpty() && cur[0] <= out.get(out.size() - 1)[1]) {
                    int[] last = out.get(out.size() - 1);
                    last[1] = Math.max(last[1], cur[1]);       // overlaps the last one: stretch it
                } else {
                    out.add(new int[]{cur[0], cur[1]});        // a gap: start a new interval
                }
            }
            return out.toArray(new int[0][]);
        }
    }

    C++

    class Solution {
    public:
        vector<vector<int>> merge(vector<vector<int>>& intervals) {
            sort(intervals.begin(), intervals.end());          // by start (then end)
            vector<vector<int>> out;
            for (const vector<int>& cur : intervals) {
                if (!out.empty() && cur[0] <= out.back()[1]) {
                    out.back()[1] = max(out.back()[1], cur[1]);   // overlaps the last one: stretch it
                } else {
                    out.push_back(cur);                            // a gap: start a new interval
                }
            }
            return out;
        }
    };

    Python

    class Solution:
        def merge(self, intervals: list[list[int]]) -> list[list[int]]:
            intervals.sort(key=lambda x: x[0])                 # by start
            out = []
            for a, b in intervals:
                if out and a <= out[-1][1]:
                    out[-1][1] = max(out[-1][1], b)            # overlaps the last one: stretch it
                else:
                    out.append([a, b])                         # a gap: start a new interval
            return out

    Common mistakes

    • Skipping the sort because the example happens to be sorted.
    • Setting the end to e instead of max(lastEnd, e), which shrinks [1, 4] to [1, 3] when [2, 3] follows.
    • Using < instead of ≤, so touching intervals stay apart.

    Similar problems