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[start, end]
Example 1
Output: 1
Explanation: remove [1,3], and the other three no longer overlap.
Example 2
Output: 2
Explanation: only one copy of [1,2] can stay.
Example 3
Output: 0
Explanation: the two intervals only touch at 2.
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.
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 lastEndlastEndlastEnd
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 lastEndInteger.MIN_VALUEintkeptkept
Java Solution
The method eraseOverlapIntervals
- First, copy the array with
intointervals.clone() , so the caller's array keeps its order. Then sortsorted by end withsorted and the comparatorArrays.sort , which compares the ends of two intervals.(a, b) -> Integer.compare(a[1], b[1]) - Set
to 0 andkept tolastEnd , since nothing is kept yet.Integer.MIN_VALUE - Loop over each interval
iniv . If its start,sorted , is at leastiv[0] , it fits: add 1 tolastEnd and setkept to its end,lastEnd . Otherwise it overlaps the last kept interval and is left out.iv[1] - After the loop, return
, the number of intervals left out.sorted.length - kept
The main
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:
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
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 lastEndInteger.MIN_VALUE
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
holds a reference to each of the n intervals, while the pass itself only needssorted andkept .lastEnd