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, firstListsecondList[a, b][5, 5]
Example 1
Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]
Example 2
Output: []
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.
Start at the left. [0, 2][1, 5][1, 2][5, 10][1, 5][5, 5]
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][15, 24][5, 10][1, 5][8, 12]
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][5, 10][1, 5][5, 10][8, 12]
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 lohi[5, 10][8, 12]lohi
If lohi[13, 23][8, 12]lohilohi[5, 10][1, 5][5, 5]
Which interval to step past
How does the walk keep its place? It keeps one index into each list, ij
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 ji
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 ijsecondList[]
Java Solution
The method intervalIntersectionint[][]firstsecond
- First, create an empty
namedArrayList for the shared intervals, and set the two indexes,result intoi andfirst intoj , to 0.second - Walk both lists with a
loop that runs as long aswhile andi are both inside their arrays.j - Inside the loop, set
to the later start withlo andMath.max to the earlier end withhi . IfMath.min , addlo <= hi to[lo, hi] .result - Still inside the loop, compare the two ends. If
ends beforefirst[i] , movesecond[j] forward; otherwise, including a tie, movei forward.j - Once either list runs out, the loop stops. Turn
into anresult withint[][] and return it.toArray
The main
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:
[[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[][0, 10]j[1, 2][4, 5][8, 12][0, 10]
The fourth line, [[3, 3]][1, 3][3, 5][1, 3][2, 3]j[5, 5][3, 4][1, 2][6, 7]
What if both indexes moved after every overlap? A version that does that prints [[1, 2], [8, 10], [15, 23], [25, 25]][5, 5][24, 24][0, 2][1, 5][1, 5][5, 10]
Complexity
All the work happens in the while
- Time: O(m + n), because every pass of the loop moves
ori forward by one, and together they can move at most m + n times over the two lists.j - Space: O(m + n) for the answer, because each pass adds at most one interval to
, and apart from it the method keeps onlyresult ,i ,j andlo .hi
Looking for the gaps that no interval covers, instead of the stretches both lists share, is the problem in