Merge Intervals

Join every group of overlapping intervals into one, so the result covers the same numbers with no overlaps.

Given an array of intervals, where each interval [start, end] covers the numbers from start to end, merge all intervals that overlap. Return intervals that cover exactly the same numbers as the input, with no two of them overlapping. Intervals that only touch, such as [1, 4] and [4, 5], count as overlapping.

Example 1
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Example 2
Input: intervals = [[1,4],[4,5]]
Output: [[1,5]]
Solution

The Idea

Picture a meeting room that four people have booked for one day: from 1 to 3, from 2 to 6, from 8 to 10 and from 15 to 18. Each booking is an interval: a stretch of time with a start and an end. You want to know when the room is busy, written as few stretches as possible.

The bookings 1 to 3 and 2 to 6 share the time from 2 to 3, so the room is busy from 1 to 6 without a break. The booking from 8 to 10 starts after 6, so there is a free gap before it. That is Example 1: [1, 3] and [2, 6] become [1, 6], and the other two stay as they are.

With four bookings this is easy to see. But the input can come in any order, with [8, 10] first and [1, 3] last. So how do we find which intervals overlap, without comparing each one with all the others?

Sort them by start first. Then walk through them in that order and build the result as you go. Look at the picture below.

Example 1 on a number line, sorted by start. [2, 6] starts at 2, before [1, 3] ends at 3, so they overlap and merge into [1, 6]. [8, 10] starts at 8, after 6, so there is a gap, and so does [15, 18]. The merged row is [1, 6], [8, 10], [15, 18].

The rows labelled "input, sorted by start" show the four intervals above a number line. [2, 6] starts at 2, before [1, 3] ends at 3: overlap. The two join, and the stretch now ends at 6. [8, 10] starts at 8, after 6: a gap, so a new stretch begins. [15, 18] starts after 10, another gap. The row labelled "merged" is the answer.

Notice that each interval was compared only with the stretch being built, the last one in the merged row. That is enough once the input is sorted. Every earlier stretch ended before the last one started, and the current interval starts no earlier than the last one did, so it cannot reach back to an earlier stretch.

Solution Approach

Turning that idea into code means settling four things: why sorting beats comparing every pair, how to sort without disturbing the input, when an interval joins the last merged one, and how far to stretch it.

Comparing every pair

Why not simply check each interval against all the others? That is about n² comparisons for n intervals, and one pass is not even enough. In [[1, 3], [5, 7], [2, 6]], the first two do not overlap each other, yet both overlap [2, 6], so a merge can make new overlaps that need another round. Sorting by start lets one pass handle every chain like that.

Sorting a copy by start

What should the sort compare? Only the starts, the first number of each pair: Integer.compare(a[0], b[0]). Sorting intervals itself would reorder the caller's array, so the code sorts a copy made with intervals.clone().

That copy is shallow: it is a new outer array, but its pairs are the same int[] objects as in the input. So the result must never change a pair in place. It stores fresh two-number arrays, and stretching those leaves the input untouched.

Joining the last merged interval

When does an interval join the last merged one, called last? When it starts at or before the end of last, that is, iv[0] <= last[1], where iv is the current interval. The <= and not < is what joins touching intervals such as [1, 4] and [4, 5]. Otherwise there is a gap, and iv starts a new merged interval.

Stretching to the larger end

How far does last stretch when iv joins it? Not always to the end of iv. In [[1, 10], [2, 3]], the second interval sits completely inside the first, and taking its end would shrink the stretch to 3. Taking Math.max(last[1], iv[1]) keeps whichever end reaches further.

Java Solution

The method merge works in these steps:

  1. First, copy the input with intervals.clone() into sorted, and sort that copy by start with Arrays.sort and a comparator that, for two intervals a and b, compares their starts a[0] and b[0].
  2. Create an empty list, merged, to collect the result intervals.
  3. Walk through sorted with one loop, taking each interval as iv. Inside, last is the last interval in merged, or null while merged is still empty.
  4. If last exists and iv[0] <= last[1], the two overlap: set last[1] to Math.max(last[1], iv[1]).
  5. Otherwise, add a fresh copy of iv, new int[] {iv[0], iv[1]}, to merged.
  6. After the loop, turn merged into an int[][] with toArray and return it.

The main method runs both examples, one interval inside another, an unsorted input where merges chain, a single interval, and a check that the caller's array keeps its order.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MergeIntervals {

    public static int[][] merge(int[][] intervals) {
        int[][] sorted = intervals.clone();
        Arrays.sort(sorted, (a, b) -> Integer.compare(a[0], b[0]));   // by start

        List<int[]> merged = new ArrayList<>();
        for (int[] iv : sorted) {
            int[] last = merged.isEmpty() ? null : merged.get(merged.size() - 1);
            if (last != null && iv[0] <= last[1]) {
                last[1] = Math.max(last[1], iv[1]);   // overlaps: stretch the last interval
            } else {
                merged.add(new int[] {iv[0], iv[1]}); // a gap: start a new interval
            }
        }
        return merged.toArray(new int[0][]);
    }

    static void show(int[][] intervals) {
        System.out.println(Arrays.deepToString(merge(intervals)));
    }

    public static void main(String[] args) {
        show(new int[][] {{1, 3}, {2, 6}, {8, 10}, {15, 18}});
        show(new int[][] {{1, 4}, {4, 5}});
        show(new int[][] {{1, 10}, {2, 3}});               // one inside another
        show(new int[][] {{8, 10}, {1, 3}, {9, 12}, {2, 6}}); // not sorted
        show(new int[][] {{5, 7}});

        int[][] input = {{8, 10}, {1, 3}, {2, 6}};
        show(input);
        System.out.println("input after: " + Arrays.deepToString(input));
    }
}

Running it prints:

Output
[[1, 6], [8, 10], [15, 18]]
[[1, 5]]
[[1, 10]]
[[1, 6], [8, 12]]
[[5, 7]]
[[1, 6], [8, 10]]
input after: [[8, 10], [1, 3], [2, 6]]

The first line, [[1, 6], [8, 10], [15, 18]], is the merged row from the picture. The second, [[1, 5]], comes from the touching pair [1, 4] and [4, 5]. With < in place of <=, that line prints [[1, 4], [4, 5]] instead.

The third line, [[1, 10]], is the Math.max at work: setting last[1] to iv[1] alone turns it into [[1, 3]]. The fourth input, [[8, 10], [1, 3], [9, 12], [2, 6]], sorts to [1, 3], [2, 6], [8, 10], [9, 12], and both overlaps merge, giving [[1, 6], [8, 12]].

A single interval, [5, 7], comes back as [[5, 7]]. The last line shows the array input after merging it: still [[8, 10], [1, 3], [2, 6]], in its original order, because only the copy was sorted and only fresh pairs were stretched.

Complexity

The work is one sort followed by one pass over the sorted intervals.

  • Time: O(n log n), because sorting the n intervals by start takes O(n log n) comparisons, and the pass after it does a fixed amount of work for each interval.
  • Space: O(n), because the sorted copy holds n references to the pairs, and merged holds up to n new pairs when no two intervals overlap.

When the intervals are already sorted and merged, adding one more takes only O(n): see Insert Interval.