Insert Interval

Add a new interval to a sorted list of intervals, merging it with every interval it overlaps, in one pass.

Each interval is a pair [start, end]. Given a list of intervals that do not overlap and are sorted by start, insert newInterval into it. The list must stay sorted by start and free of overlaps, so merge the new interval with every interval it overlaps. Intervals that share an end point, such as [4, 8] and [8, 10], count as overlapping.

Example 1
Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]
Example 2
Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Explanation: [4,8] overlaps [3,5], [6,7] and [8,10].
Solution

The Idea

Picture a day planner with some hours already blocked out: 1 to 2, 3 to 5, 6 to 7, 8 to 10 and 12 to 16. Each block is an interval, a stretch from a start to an end, written [3, 5]. Now a new block from 4 to 8 comes in. Where does it go, and what happens to the blocks it runs into?

Look at the picture below. It shows Example 2 on a number line, with the new interval [4, 8] in the middle row.

Example 2 on a number line. [1, 2] is before the new interval [4, 8]; [3, 5], [6, 7] and [8, 10] overlap it; [12, 16] is after it. The result is [1, 2], [3, 10], [12, 16].

In the row labelled "existing intervals", [1, 2] ends at 2, before the new interval starts at 4, so it is not touched. It is marked "before". [3, 5] and [6, 7] reach into the stretch from 4 to 8. [8, 10] starts at 8, exactly where the new interval ends, so it touches it. These three are marked "overlapping". [12, 16] starts after 8 and is marked "after".

Notice the order of the labels: all "before" intervals come first, then all "overlapping" ones, then all "after" ones. That is no accident. The list is sorted by start and has no overlaps, so its intervals sit one after another along the line, and the new interval covers one connected stretch of it. So how do we tell which group each interval belongs to? By walking the list once, from left to right, and noticing where one group gives way to the next.

The overlapping group and the new interval then join into one interval. It starts at the smallest start among them, 3, and ends at the largest end, 10. That is [3, 10] in the row labelled "result", placed between [1, 2] and [12, 16], which are copied unchanged.

Solution Approach

Sorting again after adding works but does extra work, so one pass is used instead, settling three things: where the "before" group ends, how the new interval grows, and where the grown interval goes.

Adding and sorting again

Why not append newInterval to the list, sort by start, and join overlapping neighbours, as Merge Intervals does? It gives the right answer, but sorting n intervals takes O(n log n) time. The list is already sorted, so walking it once, in O(n), is enough.

Where the "before" group ends

The walk moves an index i along the list. Which intervals are safe to copy straight away? Those that end before the new interval starts: intervals[i][1] < start, where start is the new interval's start. The comparison is strictly less than on purpose. An interval ending exactly at start touches the new one, and touching intervals must merge.

Growing the new interval

Once an interval no longer ends before start, how do we know it overlaps? It is enough that it starts at or before the new interval's end, kept in a variable named end: intervals[i][0] <= end. It did not end before start, so its end reaches start or beyond, and the two meet somewhere.

Each such interval widens the new one: start becomes the smaller of the two starts and end the larger of the two ends. In Example 2, [3, 5] turns [4, 8] into [3, 8], [6, 7] changes nothing, and [8, 10] makes it [3, 10]. Then [12, 16] starts at 12, after 10, and the growing stops.

Where the grown interval goes

Where does [start, end] go in the result? Right after the "before" group, added once, when the growing stops. If nothing overlapped, it goes there unchanged, between the last interval that ends before it and the first that starts after it. Everything left after that starts after end, so it is copied as it is.

Java Solution

The method insert works in these steps:

  1. First, create an empty list result, set an index i to 0 and n to the number of intervals, and copy the new interval's ends into start and end.
  2. A first loop copies the "before" group: while intervals[i][1] < start, it adds intervals[i] to result and moves i on.
  3. A second loop, starting where the first stopped, grows the new interval: while intervals[i][0] <= end, it sets start to the smaller start and end to the larger end, and moves i on.
  4. Add [start, end] to result.
  5. A third loop copies the rest of intervals into result, and the method returns result as an array with result.toArray(new int[0][]).

The main method runs both examples, then an empty list, a new interval that only touches one interval, and new intervals that fall before all, after all, and over all the existing ones.

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

public class InsertInterval {

    public static int[][] insert(int[][] intervals, int[] newInterval) {
        List<int[]> result = new ArrayList<>();
        int i = 0;
        int n = intervals.length;
        int start = newInterval[0];
        int end = newInterval[1];

        while (i < n && intervals[i][1] < start) {
            result.add(intervals[i++]);           // ends before the new one starts
        }
        while (i < n && intervals[i][0] <= end) {
            start = Math.min(start, intervals[i][0]);   // overlaps: widen to cover it
            end = Math.max(end, intervals[i][1]);
            i++;
        }
        result.add(new int[] {start, end});
        while (i < n) {
            result.add(intervals[i++]);           // starts after the new one ends
        }
        return result.toArray(new int[0][]);
    }

    public static void main(String[] args) {
        System.out.println(Arrays.deepToString(
            insert(new int[][] {{1, 3}, {6, 9}}, new int[] {2, 5})));
        System.out.println(Arrays.deepToString(
            insert(new int[][] {{1, 2}, {3, 5}, {6, 7}, {8, 10}, {12, 16}}, new int[] {4, 8})));
        System.out.println(Arrays.deepToString(
            insert(new int[][] {}, new int[] {5, 7})));
        System.out.println(Arrays.deepToString(
            insert(new int[][] {{1, 2}}, new int[] {2, 3})));
        System.out.println(Arrays.deepToString(
            insert(new int[][] {{3, 4}, {6, 7}}, new int[] {1, 2})));
        System.out.println(Arrays.deepToString(
            insert(new int[][] {{3, 4}, {6, 7}}, new int[] {9, 10})));
        System.out.println(Arrays.deepToString(
            insert(new int[][] {{3, 4}, {6, 7}}, new int[] {1, 10})));
    }
}

Running it prints:

Output
[[1, 5], [6, 9]]
[[1, 2], [3, 10], [12, 16]]
[[5, 7]]
[[1, 3]]
[[1, 2], [3, 4], [6, 7]]
[[3, 4], [6, 7], [9, 10]]
[[1, 10]]

[[1, 5], [6, 9]] and [[1, 2], [3, 10], [12, 16]] match the two examples, with [4, 8] grown into [3, 10] as in the picture. The third line, [[5, 7]], comes from the empty list: all three loops are skipped, so the result holds just the new interval.

Look at the fourth line, [[1, 3]]: [1, 2] and [2, 3] share only the point 2, and they are merged. That depends on the strict < in the first loop. With <= there, the first loop copies [1, 2] as a "before" interval, and that line prints [[1, 2], [2, 3]], two intervals that touch.

The last three lines all insert into [[3, 4], [6, 7]]. The new interval [1, 2] goes in front, because no interval ends before 1 and the first one starts after 2. [9, 10] goes at the back, because both intervals end before 9. [1, 10] swallows both and leaves a single interval.

Complexity

The three loops share one index i, which only moves forward, so the list is walked once in total.

  • Time: O(n), because i passes each of the n existing intervals once across the three loops, and toArray copies at most n + 1 entries.
  • Space: O(n) for the result, because result holds up to n + 1 intervals, while the walk itself keeps only start, end and i.