Interval List Intersections

Find the stretches of numbers that two sorted lists of intervals both cover, in one pass over both lists.

Given two lists of closed intervals, firstList and secondList, return every stretch of numbers that both lists cover. A closed interval [a, b] holds every number from a to b, both ends included, so [5, 5] is just the number 5. Each list is sorted by start, and no two intervals in the same list share a number. Return the shared stretches as closed intervals, from left to right.

Example 1
Input: firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15,24],[25,26]]
Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]
Example 2
Input: firstList = [[1,3],[5,9]], secondList = []
Output: []
Solution

The Idea

Picture two friends trying to find a time for a call. Each writes down when they are free, in order: the first friend is free from time 0 to time 2, then from 5 to 10, from 13 to 23 and from 24 to 25. That is Example 1's first list, and the second friend's free times are the second list. They can only talk when both are free.

Look at the picture below. The row labelled first list shows the first friend's intervals, the row labelled second list shows the second friend's, and the row labelled covered by both shows the answer.

Example 1 on a number line from 0 to 26. The first list is [0, 2], [5, 10], [13, 23], [24, 25]; the second list is [1, 5], [8, 12], [15, 24], [25, 26]. The row covered by both shows [1, 2], [5, 5], [8, 10], [15, 23], [24, 24] and [25, 25].

Start at the left. [0, 2] and [1, 5] share the numbers from 1 to 2, so the bottom row begins with [1, 2]. Next, [5, 10] starts at 5, exactly where [1, 5] ends. Both intervals include their ends, so they share the single number 5, drawn as a dot: [5, 5]. The dots at 24 and 25 come about in the same way.

Finding what two intervals share is easy once they are side by side. The harder question is which intervals to put side by side. [13, 23] meets only [15, 24], while [5, 10] meets two intervals, [1, 5] and [8, 12]. How do we find every meeting without checking each interval against the whole other list?

Read the picture from left to right, the way the friends would go through their day, keeping one current interval from each list. Of the two current intervals, take the one that ends first. The current interval in the other list ends at the same point or later, and the intervals after it in that list start after it ends. Once the two current intervals are compared, nothing is left for the interval that ends first to meet, and it can be dropped.

The other interval stays, because it may still meet the next interval of the other list. In the picture, [1, 5] ends before [5, 10], so [1, 5] is dropped, and [5, 10] goes on to meet [8, 12]. So the whole answer comes from one walk through both lists at once, always stepping past the interval that ends first.

Solution Approach

Turning that walk into code means settling three things, after a quick look at the slow way: how to find the shared part of two intervals, which interval to step past after each comparison, and when the walk ends.

Comparing every pair

Why not compare every interval of the first list with every interval of the second? It works, but it is slow. With m intervals in the first list and n in the second, that is m × n comparisons: 16 for Example 1, but a million for two lists of 1,000 intervals each. Most of them find nothing, because intervals far apart on the line cannot meet. The walk only compares intervals that are next to each other on the line.

The shared part of two intervals

Where do two intervals overlap? The shared part cannot start before both intervals have started, so it starts at the later start. It cannot go on after either interval has ended, so it ends at the earlier end. Call these two numbers lo and hi: for [5, 10] and [8, 12], lo is 8 and hi is 10.

If lo is greater than hi, the intervals do not meet: [13, 23] and [8, 12] give lo = 13 and hi = 12. If lo equals hi, as with [5, 10] and [1, 5], the intervals share one number, and [5, 5] goes into the answer.

Which interval to step past

How does the walk keep its place? It keeps one index into each list, i for the first and j for the second. After each comparison, the index of the interval with the smaller end moves forward by one. Walking two lists side by side like this, one index in each, is known as the two-pointer technique.

Only one index moves, even after an overlap, because the interval that ends later may still meet the next interval of the other list. When both ends are equal, either index may move. The code moves j. The next interval of the second list starts after that shared end, so it cannot meet the first list's current interval, and on the next round i moves too.

When the walk ends

When can the walk stop? As soon as one list runs out, because the intervals left in the other list have nothing to meet. So the loop runs only while i and j both point at an interval. That also covers Example 2: secondList is empty, the loop never runs, and the answer is [].

Java Solution

The method intervalIntersection takes the two lists as int[][] arrays named first and second, where each row is one interval, start then end. It works in these steps:

  1. First, create an empty ArrayList named result for the shared intervals, and set the two indexes, i into first and j into second, to 0.
  2. Walk both lists with a while loop that runs as long as i and j are both inside their arrays.
  3. Inside the loop, set lo to the later start with Math.max and hi to the earlier end with Math.min. If lo <= hi, add [lo, hi] to result.
  4. Still inside the loop, compare the two ends. If first[i] ends before second[j], move i forward; otherwise, including a tie, move j forward.
  5. Once either list runs out, the loop stops. Turn result into an int[][] with toArray and return it.

The main method runs both examples, one long interval that covers several short ones, two intervals that touch at one number, two intervals that end at the same number, and two lists that never meet.

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

public class IntervalListIntersections {

    public static int[][] intervalIntersection(int[][] first, int[][] second) {
        List<int[]> result = new ArrayList<>();
        int i = 0;
        int j = 0;
        while (i < first.length && j < second.length) {
            int lo = Math.max(first[i][0], second[j][0]);   // the later start
            int hi = Math.min(first[i][1], second[j][1]);   // the earlier end
            if (lo <= hi) {
                result.add(new int[] {lo, hi});             // both cover lo to hi
            }
            if (first[i][1] < second[j][1]) {
                i++;                                        // first[i] ends first: done with it
            } else {
                j++;                                        // second[j] ends first, or both tie
            }
        }
        return result.toArray(new int[0][]);
    }

    public static void main(String[] args) {
        print(new int[][] {{0, 2}, {5, 10}, {13, 23}, {24, 25}},
              new int[][] {{1, 5}, {8, 12}, {15, 24}, {25, 26}});
        print(new int[][] {{1, 3}, {5, 9}}, new int[][] {});
        print(new int[][] {{0, 10}}, new int[][] {{1, 2}, {4, 5}, {8, 12}});
        print(new int[][] {{1, 3}}, new int[][] {{3, 5}});
        print(new int[][] {{1, 3}, {5, 6}}, new int[][] {{2, 3}, {4, 5}});
        print(new int[][] {{1, 2}, {6, 7}}, new int[][] {{3, 4}});
    }

    static void print(int[][] first, int[][] second) {
        System.out.println(Arrays.deepToString(intervalIntersection(first, second)));
    }
}

Running it prints:

Output
[[1, 2], [5, 5], [8, 10], [15, 23], [24, 24], [25, 25]]
[]
[[1, 2], [4, 5], [8, 10]]
[[3, 3]]
[[2, 3], [5, 5]]
[]

Example 1 comes back as the bottom row of the picture, single numbers included, and the empty secondList of Example 2 gives []. In the third line, [0, 10] stays current while j moves through [1, 2], [4, 5] and [8, 12]. One interval of the first list gives three answers, and the last is cut off at 10, where [0, 10] ends.

The fourth line, [[3, 3]], is [1, 3] meeting [3, 5] at the number 3. The fifth line shows a tie: [1, 3] and [2, 3] both end at 3, j moves first, and the walk still goes on to find [5, 5]. The last line is empty because [3, 4] falls in the gap between [1, 2] and [6, 7].

What if both indexes moved after every overlap? A version that does that prints [[1, 2], [8, 10], [15, 23], [25, 25]] for Example 1, missing [5, 5] and [24, 24]. After [0, 2] meets [1, 5], both move on, so [1, 5] is never compared with [5, 10].

Complexity

All the work happens in the while loop, and each pass of it does a fixed amount of work.

  • Time: O(m + n), because every pass of the loop moves i or j forward by one, and together they can move at most m + n times over the two lists.
  • Space: O(m + n) for the answer, because each pass adds at most one interval to result, and apart from it the method keeps only i, j, lo and hi.

Looking for the gaps that no interval covers, instead of the stretches both lists share, is the problem in Employee Free Time.