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]startend[1, 4][4, 5]
Example 1
Output: [[1,6],[8,10],[15,18]]
Example 2
Output: [[1,5]]
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][2, 6][1, 6]
With four bookings this is easy to see. But the input can come in any order, with [8, 10][1, 3]
Sort them by start first. Then walk through them in that order and build the result as you go. Look at the picture below.
The rows labelled "input, sorted by start" show the four intervals above a number line. [2, 6][1, 3][8, 10][15, 18]
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]][2, 6]
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])intervalsintervals.clone()
That copy is shallow: it is a new outer array, but its pairs are the same int[]
Joining the last merged interval
When does an interval join the last merged one, called lastlastiv[0] <= last[1]iv<=<[1, 4][4, 5]iv
Stretching to the larger end
How far does lastiviv[[1, 10], [2, 3]]Math.max(last[1], iv[1])
Java Solution
The method merge
- First, copy the input with
intointervals.clone() , and sort that copy by start withsorted and a comparator that, for two intervalsArrays.sort anda , compares their startsb anda[0] .b[0] - Create an empty list,
, to collect the result intervals.merged - Walk through
with one loop, taking each interval assorted . Inside,iv is the last interval inlast , ormerged whilenull is still empty.merged - If
exists andlast , the two overlap: setiv[0] <= last[1] tolast[1] .Math.max(last[1], iv[1]) - Otherwise, add a fresh copy of
,iv , tonew int[] {iv[0], iv[1]} .merged - After the loop, turn
into anmerged withint[][] and return it.toArray
The main
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:
[[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]][[1, 5]][1, 4][4, 5]<<=[[1, 4], [4, 5]]
The third line, [[1, 10]]Math.maxlast[1]iv[1][[1, 3]][[8, 10], [1, 3], [9, 12], [2, 6]][1, 3], [2, 6], [8, 10], [9, 12][[1, 6], [8, 12]]
A single interval, [5, 7][[5, 7]]input[[8, 10], [1, 3], [2, 6]]
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
holds up to n new pairs when no two intervals overlap.merged
When the intervals are already sorted and merged, adding one more takes only O(n): see