Problem Description
You are given an array of intervals intervals, where intervals[i] = [starti, endi].
Write a function that returns the minimum number of intervals you need to remove so that the remaining intervals don't overlap.
Constraints
- The array length is in the range from 1 to 105
- Each element of the array is itself an array of two elements
- Interval bounds are in the range from -5 * 104 to 5 * 104
- The start of an interval is always less than its end
Examples
Input: [[1,2],[2,3],[3,4],[1,3]]
Answer: 1
The interval [1,3] can be removed, and the rest don't overlap.
Solution
Consider the two intervals with the earliest end times.
Let's say the earlier end time is x and the later one is y, so x < y.
If we can keep only one of them, should we pick the one ending at x or the one ending at y?
To avoid overlaps, we should always greedily pick the interval with the earlier end time x.
The reasoning goes like this:
- We pick either
xory. Let's call our choicek. - To avoid an overlap, the start time of the next interval we pick must be greater than or equal to
k. - We want to maximize the number of intervals we keep (without overlaps), so we want to maximize the choice for the next interval.
- Since the start time of the next interval must be greater than or equal to
k, a largerkcan never give us more options than a smallerk. - So we should try to minimize
k. Therefore, we should always greedily pickx, sincex < y.
In general, k is the end time of the most recently kept interval.
We start by sorting the intervals by end time so that we can process them in order.
Now, for the current interval with start x and end y, since we sorted by end time, y must be greater than k.
This leaves two options:
- Option 1,
x >= k: we can safely keep this interval, since it doesn't cause an overlap. - Option 2,
x < k: keeping this interval would cause an overlap. As we established earlier, we should always keep intervals with earlier end times. Sincey > k, we must remove the current interval.
export const eraseOverlapIntervals = (intervals: number[][]): number => {
intervals.sort((a, b) => {
return a[1] - b[1];
});
let res = 0;
let k = intervals[0][1];
for (let i = 1; i < intervals.length; i++) {
const end = intervals[i][1];
const start = intervals[i][0];
if (start >= k) {
k = end;
} else {
res++;
}
}
return res;
};Complexity Analysis
Time Complexity
To find the answer, it's enough to go through the array once, which is O(n).
However, we sort the array beforehand, which most likely costs O(n log n).
So the overall time complexity is O(n log n).
Space Complexity
We don't create variables that depend on the input size, but sorting also requires memory.
Different languages use different sorting algorithms, so the space complexity varies from O(log n) to O(n).