Find Right Interval
For every interval, find the interval with the smallest start that is at or after its end.
Given a list of intervals, each written as [start, end]iii
Return an array that holds, for each interval, the index of its right interval, or -1 if it has none.
Example 1
Output: [-1]
Example 2
Output: [-1, 0, 1]
Explanation: [2, 3] ends at 3, and [3, 4] starts at 3. [1, 2] ends at 2, and [2, 3] starts at 2. Nothing starts at 4 or later.
Example 3
Output: [-1, 2, -1]
The Idea
Think of each interval as a booking for a room: it starts at one hour and ends at a later one. For each booking, the question is which booking could follow it soonest, starting when it ends or any time after that.
Take Example 2. The bookings are [3, 4] at index 0, [2, 3] at index 1 and [1, 2] at index 2, so the starts are 3, 2 and 1. The booking [1, 2] ends at 2. Two starts are at least 2, namely 3 and 2, and the smaller one, 2, belongs to index 1. The booking [2, 3] ends at 3, and only the start 3 qualifies, at index 0. Nothing starts at 4 or later, so [3, 4] gets -1. That gives [-1, 0, 1]
Each of those answers came from looking at every start. With three intervals that is quick, but with n intervals it is n looks for each of n intervals. Is there a way to jump straight to the start we want?
There is, once the starts are in sorted order. Look at the picture below. The top part shows the three intervals on a number line, and the bottom part shows the same starts, sorted, each with its original index.
The dashed orange line, labelled "[2, 3] ends at 3", marks the end we are matching. In the sorted row, start 1 and start 2 are smaller than 3, and start 3 is big enough. The answer is the first box that is big enough, the one labelled start 3, index 0.
So in a sorted row, the starts that are big enough always form one stretch at the end, and the answer is where that stretch begins. Finding where it begins is a job for binary search, which halves the part of the row it still has to look at with every step. The index written under each start tells us which interval it came from.
Solution Approach
After a look at what the simple way costs, turning that idea into code means settling three things: how to keep each start's original index through the sort, how the binary search finds the first start that is big enough, and what it returns when there is none. A shorter, optional version with a ready-made Java class comes last.
Checking every start
What does the simple way cost? For each interval, walk through all the starts and keep the smallest one that is at least its end. That is n steps for each of the n intervals, so about n² steps. With 10,000 intervals it is 100 million comparisons.
Sorting the starts with their indexes
Why not just sort the starts? Because the answer must be an index in the list as it was given, and sorting moves the starts to new positions. So each start travels with its index as a pair, {start, index}{1, 2}{2, 1}{3, 0}
The starts are sorted once, and every interval then searches the same sorted row. That is why sorting pays off: one sort, then n quick searches.
Finding the first start that is big enough
How does the binary search find where the big enough starts begin? It keeps two positions, lohimid
If that start is less than the end, it and everything to its left are too small, so lomid + 1himidlohi
A start equal to the end counts, because the problem asks for a start that is at least the end. That is how [2, 3] finds [3, 4] in Example 2, and how a single interval [1, 1] is its own right interval.
When no start is big enough
What happens for [3, 4] in Example 2, where every start is smaller than 4? Each step moves lololo == n
Optional: a TreeMap instead of the hand-written search
Java's TreeMapmap.ceilingEntry(end)endnull
Java Solution
The method findRightInterval
- First, build an array
with one pairstarts per interval, so{start, index} holdsstarts[i] andintervals[i][0] .i - Sort
by start, withstarts and a comparator, a small function that tells the sort which of two pairs comes first. It compares their start values.Arrays.sort - Create the array
, then loop over the intervals in their original order. For intervalresult , read its end intoi .end - Inside that loop, run the binary search:
starts at 0 andlo athi , the number of intervals. Whilen is belowlo , compare the start athi withmid . Too small movesend tolo , otherwisemid + 1 moves tohi .mid - When the search stops, store -1 in
ifresult[i] equalslo , and otherwise the original index kept inn .starts[lo][1] - After the loop, return
.result
The main
import java.util.Arrays;
public class FindRightInterval {
public static int[] findRightInterval(int[][] intervals) {
int n = intervals.length;
int[][] starts = new int[n][];
for (int i = 0; i < n; i++) {
starts[i] = new int[] {intervals[i][0], i}; // {start, original index}
}
Arrays.sort(starts, (x, y) -> Integer.compare(x[0], y[0]));
int[] result = new int[n];
for (int i = 0; i < n; i++) {
int end = intervals[i][1];
int lo = 0;
int hi = n;
while (lo < hi) { // first start that is >= end
int mid = lo + (hi - lo) / 2;
if (starts[mid][0] < end) {
lo = mid + 1; // too small: answer is further right
} else {
hi = mid; // big enough: answer is here or left
}
}
result[i] = (lo == n) ? -1 : starts[lo][1];
}
return result;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(findRightInterval(new int[][] {{1, 2}})));
System.out.println(Arrays.toString(
findRightInterval(new int[][] {{3, 4}, {2, 3}, {1, 2}})));
System.out.println(Arrays.toString(
findRightInterval(new int[][] {{1, 4}, {2, 3}, {3, 4}})));
System.out.println(Arrays.toString(findRightInterval(new int[][] {{1, 1}})));
System.out.println(Arrays.toString(
findRightInterval(new int[][] {{-5, -1}, {10, 20}, {0, 7}, {7, 9}})));
System.out.println(Arrays.toString(findRightInterval(new int[0][])));
}
}
Running it prints:
[-1]
[-1, 0, 1]
[-1, 2, -1]
[0]
[2, -1, 3, 1]
[]
In [-1, 0, 1][0]
The line [2, -1, 3, 1][]
The comparison starts[mid][0] < end<=[-1, -1, 0]
Complexity
The work is one sort of the starts, plus one binary search for each interval.
- Time: O(n log n), where n is the number of intervals.
sorts the n pairs in O(n log n), and each of the n searches halves the row of starts at every step, so it takes about log n steps.Arrays.sort - Space: O(n), because
holds a pair of two values for every interval, next to thestarts array that is returned.result
The same search for the first position whose value is at least a target is the whole solution of