You are given an array of intervals intervals
where intervals[i] = [start_i, end_i]
represent the start and end of the ith interval. Return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Example 1:
Input: intervals = [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: [1,3] can be removed and the rest of the intervals are non-overlapping.
Example 2:
Input: intervals = [[1,2],[1,2],[1,2]]
Output: 2
Explanation: You need to remove two [1,2] to make the rest of the intervals non-overlapping.
Example 3:
Input: intervals = [[1,2],[2,3]]
Output: 0
Explanation: You don't need to remove any of the intervals since they're already non-overlapping.
import java.util.Arrays;
public class Solution {
public int eraseOverlapIntervals(int[][] intervals) {
if (intervals.length == 0) {
return 0;
}
// Sort the intervals based on their end time
Arrays.sort(intervals, (a, b) -> Integer.compare(a[1], b[1]));
int end = intervals[0][1];
int count = 0;
for (int i = 1; i < intervals.length; i++) {
if (intervals[i][0] < end) {
// We need to remove this interval
count++;
} else {
// Update the end to be the end of this interval
end = intervals[i][1];
}
}
return count;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[][] intervals1 = // use example above
System.out.println(sol.eraseOverlapIntervals(intervals1)); // Output: 1
int[][] intervals2 = // use example above
System.out.println(sol.eraseOverlapIntervals(intervals2)); // Output: 2
int[][] intervals3 = // use example above
System.out.println(sol.eraseOverlapIntervals(intervals3)); // Output: 0
}
}
Thus, the overall time complexity is O(n log n) due to the sorting step.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?