SDE & MLE Prep

435. Non-overlapping Intervals

Problem

Return the minimum number of intervals to remove so that the rest don't overlap. Intervals that only touch (like [1,2] and [2,3]) don't overlap.

Example: [[1,2],[2,3],[3,4],[1,3]] → 1; [[1,2],[1,2],[1,2]] → 2

Constraints: up to 10⁵ intervals.

Min removals = n − (max non-overlapping set). Greedy activity selection: sort by end, keep an interval if it starts at/after the last kept end.

Complexity: O(n log n).

class Solution:
    def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
        keep, end = 0, float("-inf")
        for s, e in sorted(intervals, key=lambda x: x[1]):
            if s >= end:
                keep += 1
                end = e
        return len(intervals) - keep