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], where no two intervals have the same start, find the right interval of each one. The right interval of interval i is the interval with the smallest start that is still at least the end of i. It may be i itself.

Return an array that holds, for each interval, the index of its right interval, or -1 if it has none.

Example 1
Input: [[1, 2]]
Output: [-1]
Example 2
Input: [[3, 4], [2, 3], [1, 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
Input: [[1, 4], [2, 3], [3, 4]]
Output: [-1, 2, -1]
Solution

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 intervals [3, 4], [2, 3] and [1, 2] on a number line. [2, 3] ends at 3, and [3, 4] starts at 3. Below, the starts, sorted, each with its original index: start 1 index 2, start 2 index 1, start 3 index 0. The first start that is at least 3 is start 3, so the answer is index 0.

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}, and the pairs are sorted by start. Example 2 becomes {1, 2}, {2, 1}, {3, 0}, the three boxes in the picture.

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, lo and hi, and the answer always lies between them. They begin at 0 and at n, one past the last position. Each step looks at the start in the middle, at position mid.

If that start is less than the end, it and everything to its left are too small, so lo moves to mid + 1. Otherwise the start is big enough. It may be the answer, or a big enough start may sit further left, so hi moves to mid. When lo and hi meet, they stand on the first start that is at least the end. A search for the first value that is at least a target is often called a lower bound search.

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 lo right, and the search ends with lo equal to n, a position past the end of the row. So lo == n means "no right interval", and the answer is -1.

Optional: a TreeMap instead of the hand-written search

Java's TreeMap is a map that keeps its keys in sorted order. With each start as a key and its index as the value, map.ceilingEntry(end) returns the entry with the smallest key that is at least end, or null if there is none. It does the same work with less code, at the cost of one map entry object per interval.

Java Solution

The method findRightInterval works in these steps:

  1. First, build an array starts with one pair {start, index} per interval, so starts[i] holds intervals[i][0] and i.
  2. Sort starts by start, with Arrays.sort and a comparator, a small function that tells the sort which of two pairs comes first. It compares their start values.
  3. Create the array result, then loop over the intervals in their original order. For interval i, read its end into end.
  4. Inside that loop, run the binary search: lo starts at 0 and hi at n, the number of intervals. While lo is below hi, compare the start at mid with end. Too small moves lo to mid + 1, otherwise hi moves to mid.
  5. When the search stops, store -1 in result[i] if lo equals n, and otherwise the original index kept in starts[lo][1].
  6. After the loop, return result.

The main method runs the three examples, a single interval [1, 1], an unsorted list with a negative interval and a gap, and an empty list.

Java
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:

Output
[-1]
[-1, 0, 1]
[-1, 2, -1]
[0]
[2, -1, 3, 1]
[]

In [-1, 0, 1], from Example 2, the 0 is [2, 3] finding [3, 4], a start equal to its end. The [0] below it comes from [1, 1] alone: its start 1 is at least its end 1, so the interval is its own right interval.

The line [2, -1, 3, 1] comes from [-5, -1], [10, 20], [0, 7] and [7, 9], given out of order. [-5, -1] ends at -1, and the first start at least -1 is 0, at index 2. [10, 20] ends after every start, so it gets -1. [0, 7] ends at 7, where [7, 9] starts, so it gets index 3. [7, 9] ends at 9, and the next start is 10, at index 1. The empty list gives the empty [] on the last line.

The comparison starts[mid][0] < end is what lets equal values count. Changed to <=, the search looks for a start strictly greater than the end, and for Example 2 that version returns [-1, -1, 0]: [2, 3] no longer finds [3, 4].

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. Arrays.sort 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.
  • Space: O(n), because starts holds a pair of two values for every interval, next to the result array that is returned.

The same search for the first position whose value is at least a target is the whole solution of Search Insert Position.