Non-overlapping Intervals: the idea to remember.
Remove the fewest intervals so the remaining half-open scheduling intervals do not overlap.
The core insight
Sort by ending time and greedily keep each interval whose start is at least the previous kept end.
Why it works
Replacing a kept interval with an earlier finishing compatible interval leaves at least as much room for every future interval.
The mistake to avoid
Touching intervals are allowed here, unlike merging closed intervals. Empty input needs no removals.
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
int eraseOverlapIntervals(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> Integer.compare(a[1], b[1]));
int kept = 0, end = Integer.MIN_VALUE;
for (int[] interval : intervals) if (interval[0] >= end) { kept++; end = interval[1]; }
return intervals.length - kept;
}Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.