Problem
Return the minimum number of intervals you must remove so that the rest are non-overlapping. Two intervals that only touch at an endpoint do not overlap.
Original: LeetCode 435: Non-overlapping Intervals.
Examples
Example 1
`intervals = [[1, 2], [2, 3], [3, 4], [1, 3]]``1`Example 2
`intervals = [[1, 2], [1, 2], [1, 2]]``2`Example 3
`intervals = [[1, 2], [2, 3]]``0`Constraints
1 <= intervals.length <= 10^5intervals[i].length == 2-5 * 10^4 <= starti < endi <= 5 * 10^4
Hints
Hint 1
You want as many intervals as possible to survive, then the answer is the number you dropped. Endpoints may coincide.
Hint 2
This is interval scheduling: sort by finishing time and take the next compatible interval.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Try every subset, which is exponential.
Optimal. Sort by end, scan once, count how many you can keep, and return n minus that count. Equivalently, count how many start before the last kept end and skip them.
Alternative. Dynamic programming on the sorted ends is correct but slower than the greedy proof.
Complexity
- Time
- O(n log n)
O(n log n) time for the sort, O(1) extra space if you sort in place.
- Space
- O(1)
Code
def erase_overlap_intervals(intervals: list[list[int]]) -> int:
intervals = sorted(intervals, key=lambda x: x[1])
kept, end = 1, intervals[0][1]
for start, finish in intervals[1:]:
if start >= end:
kept += 1
end = finish
return len(intervals) - kept
if __name__ == "__main__":
assert erase_overlap_intervals([[1, 2], [2, 3], [3, 4], [1, 3]]) == 1
assert erase_overlap_intervals([[1, 2], [1, 2], [1, 2]]) == 2
assert erase_overlap_intervals([[1, 2], [2, 3]]) == 0
print("ok")import java.util.Arrays;
public class NonOverlappingIntervals {
static int eraseOverlapIntervals(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> Integer.compare(a[1], b[1]));
int kept = 1, end = intervals[0][1];
for (int i = 1; i < intervals.length; i++) {
if (intervals[i][0] >= end) {
kept++;
end = intervals[i][1];
}
}
return intervals.length - kept;
}
public static void main(String[] args) {
if (eraseOverlapIntervals(new int[][] {{1, 2}, {2, 3}, {3, 4}, {1, 3}}) != 1) throw new AssertionError();
if (eraseOverlapIntervals(new int[][] {{1, 2}, {1, 2}, {1, 2}}) != 2) throw new AssertionError();
if (eraseOverlapIntervals(new int[][] {{1, 2}, {2, 3}}) != 0) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official samples: [[1,2],[2,3],[3,4],[1,3]] needs one removal; [[1,2],[1,2],[1,2]] needs two; [[1,2],[2,3]] needs none.
- Sorting by start and dropping the longer of two overlaps can also work, but sorting by end is the standard greedy proof.
Follow-ups
- Minimum Number of Arrows to Burst Balloons is the same greedy idea, counting groups instead of removals.
Interview script
"To remove as few as possible I keep as many as possible. I sort by end time and greedily take every interval that does not overlap the last one I kept. The answer is n minus the number I kept."
Sources (1)
- LeetCode 435: Non-overlapping Intervalsleetcode.com