Non-overlapping Intervals

Find the fewest intervals to remove so the rest do not overlap, by keeping the ones that end earliest.

Each entry of the array intervals is a pair [start, end]. Return the fewest intervals you must remove so that the ones left do not overlap. Intervals that only touch, such as [1, 2] and [2, 3], do not count as overlapping.

Example 1
Input: intervals = [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: remove [1,3], and the other three no longer overlap.
Example 2
Input: intervals = [[1,2],[1,2],[1,2]]
Output: 2
Explanation: only one copy of [1,2] can stay.
Example 3
Input: intervals = [[1,2],[2,3]]
Output: 0
Explanation: the two intervals only touch at 2.
Solution

The Idea

Picture one tennis court and a pile of booking requests, each from a start hour to an end hour. Each request is an interval: the stretch of time between its start and its end. Two requests clash when the court would be needed for both at once.

You want to turn away as few requests as possible, which is the same as accepting as many as possible. A booking that ends at 2 and one that starts at 2 do not clash: one group walks off the court as the next walks on.

Example 1 has four requests: [1, 2], [2, 3], [3, 4] and [1, 3]. The first three follow one another, each starting where the one before it ends. [1, 3] clashes with two of them, with [1, 2] between 1 and 2 and with [2, 3] between 2 and 3. Turning away [1, 3] leaves three bookings that fit, so the answer is 1. Turning away [1, 2] and [2, 3] would also clear the clash, but that costs two.

With four requests the clashes are easy to see. With hundreds, which ones should we keep? Think about the request that ends earliest of all. Any set of bookings that fit together has some booking that comes first. Swap that first booking for the earliest-ending request, which ends no later. The court is then free at the same time or sooner, so every later booking in the set still fits.

So keeping the earliest-ending request never costs us a booking. After it, the same question comes back for the requests that start at or after its end. Look at the picture below.

Example 1 sorted by end: [1, 2] kept, [2, 3] kept, [1, 3] removed because it starts at 1, before the last kept end 3, and [3, 4] kept.

The rows are the intervals of Example 1, listed from top to bottom under "sorted by end". [1, 2] ends first and is kept. [2, 3] starts at 2, exactly where [1, 2] ends, so it is kept too. The dashed line marks the "last kept end = 3", the end of [2, 3].

The next row, [1, 3], starts at 1, before 3, so it clashes with [2, 3] and is removed. The last row, [3, 4], starts at 3 and is kept. Three of the four are kept, so one is removed.

So the rule is: go through the intervals in order of their ends, and keep each one that starts at or after the end of the last one kept. Each step takes the earliest end on offer and never goes back on it. A method that builds its answer this way, one best-looking choice at a time, is called greedy. Swapping the first booking for the earliest-ending one, as worked out above, is why this greedy rule removes the fewest.

Solution Approach

Turning that rule into code starts with a look at the slow way, trying every choice, and then settles three things: the order of the intervals, the test for whether one fits, and how counting the kept intervals gives the answer.

Trying every choice

Why not simply try every way to keep or remove? Each interval is either kept or removed, so n intervals give 2n choices. That is 16 for Example 1, but over a million for 20 intervals, and each choice still has to be checked for clashes. Sorting once and then walking through the intervals replaces all of that with one pass.

Sorting by end

Why sort by the end and not by the start? Many interval problems sort by start, but here the interval that starts first can be very long. Take [[1, 100], [2, 3], [3, 4]]. Sorted by start and with the same keep-if-it-fits rule, [1, 100] comes first and is kept. Then [2, 3] and [3, 4] both start before 100, so both are removed, even though removing [1, 100] alone is enough.

Sorted by end, the same list reads [2, 3], [3, 4], [1, 100]. [2, 3] and [3, 4] are kept, and [1, 100] starts at 1, before the last kept end 4, so it is the one removed. That is one removal, the right answer.

Testing whether an interval fits

How do we know whether the next interval clashes with the ones already kept? Keep the end of the last kept interval in a variable named lastEnd. Because of the sort, every kept interval ends at or before lastEnd. So an interval that starts at or after lastEnd clears all of them, and only that one comparison is needed.

The test uses greater-or-equal, so touching intervals both stay, which is why Example 3 removes nothing. Example 2 shows the other side. All three copies of [1, 2] end at 2, the first copy is kept, and the other two start at 1, before 2, so both are removed.

The starting value and the answer

What is lastEnd before anything is kept? It starts at Integer.MIN_VALUE, the smallest number an int can hold, so the first interval always fits, even when it starts below zero. A variable named kept counts the intervals that fit. Every other interval is removed, so the answer is the number of intervals minus kept.

Java Solution

The method eraseOverlapIntervals works in these steps:

  1. First, copy the array with intervals.clone() into sorted, so the caller's array keeps its order. Then sort sorted by end with Arrays.sort and the comparator (a, b) -> Integer.compare(a[1], b[1]), which compares the ends of two intervals.
  2. Set kept to 0 and lastEnd to Integer.MIN_VALUE, since nothing is kept yet.
  3. Loop over each interval iv in sorted. If its start, iv[0], is at least lastEnd, it fits: add 1 to kept and set lastEnd to its end, iv[1]. Otherwise it overlaps the last kept interval and is left out.
  4. After the loop, return sorted.length - kept, the number of intervals left out.

The main method runs the three examples, an empty array, the list [[1, 100], [2, 3], [3, 4]] from above, and three intervals below zero.

Java
import java.util.Arrays;

public class NonOverlappingIntervals {

    public static int eraseOverlapIntervals(int[][] intervals) {
        int[][] sorted = intervals.clone();
        Arrays.sort(sorted, (a, b) -> Integer.compare(a[1], b[1]));   // by end

        int kept = 0;
        int lastEnd = Integer.MIN_VALUE;     // below every start, so the first one fits
        for (int[] iv : sorted) {
            if (iv[0] >= lastEnd) {          // starts at or after the last kept end
                kept++;
                lastEnd = iv[1];
            }
        }
        return sorted.length - kept;         // every interval not kept is removed
    }

    public static void main(String[] args) {
        System.out.println(eraseOverlapIntervals(new int[][] {{1, 2}, {2, 3}, {3, 4}, {1, 3}}));
        System.out.println(eraseOverlapIntervals(new int[][] {{1, 2}, {1, 2}, {1, 2}}));
        System.out.println(eraseOverlapIntervals(new int[][] {{1, 2}, {2, 3}}));
        System.out.println(eraseOverlapIntervals(new int[][] {}));
        System.out.println(eraseOverlapIntervals(new int[][] {{1, 100}, {2, 3}, {3, 4}}));
        System.out.println(eraseOverlapIntervals(new int[][] {{-5, -3}, {-4, -1}, {-1, 2}}));
    }
}

Running it prints:

Output
1
2
0
0
1
1

Look at the third line, 0, from Example 3. [2, 3] starts at 2, exactly the last kept end, and the test iv[0] >= lastEnd keeps it. The fourth line is 0 as well: the empty array has nothing to remove, so the loop never runs.

The fifth line, 1, comes from the long interval [1, 100], which sorts last and is the only one removed. The same loop with the sort by start prints 2 for this input, the extra removal worked out above.

The last line comes from [[-5, -3], [-4, -1], [-1, 2]]. [-5, -3] ends first and is kept. [-4, -1] starts at -4, before -3, and is removed, and [-1, 2] fits after -3. With lastEnd starting at 0 instead of Integer.MIN_VALUE, all three starts look too early, and that line prints 3.

Complexity

Most of the time goes into the sort; the keep-or-remove pass after it is quick.

  • Time: O(n log n), because sorting the n intervals by end costs O(n log n), and the pass then makes one keep-or-remove check per interval.
  • Space: O(n), because the copy sorted holds a reference to each of the n intervals, while the pass itself only needs kept and lastEnd.

Minimum Number of Arrows to Burst Balloons uses the same sort by end, with balloons in place of bookings.