Intuition
Sort by start time. When two intervals overlap, remove the one that extends further (larger end) since it is more likely to overlap with future intervals.
Explanation
Brute Force (Greedy by Start)
Sort intervals by start time. Walk through the sorted list and whenever two consecutive intervals overlap, increment a removal counter and keep the interval with the smaller end time.
This works correctly and is actually O(n log n) due to sorting. The key difference from the optimal is purely stylistic — sorting by end is the classic formulation.
Complexity: O(n log n) time for sorting, O(1) extra space (ignoring sort internals).
Implementation
import java.util.*;
class Solution {
public int eraseOverlapIntervals(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
int removals = 0;
int prevEnd = intervals[0][1];
for (int i = 1; i < intervals.length; i++) {
if (intervals[i][0] < prevEnd) {
removals++;
prevEnd = Math.min(prevEnd, intervals[i][1]);
} else {
prevEnd = intervals[i][1];
}
}
return removals;
}
}