sagelearnai

Non-overlapping Intervals

Difficulty: Medium · Pattern: Intervals · LeetCode #435

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

Examples

text
[[1, 2], [2, 3], [3, 4], [1, 3]]   →  1    (remove [1, 3])
[[1, 2], [1, 2], [1, 2]]           →  2
[[1, 2], [2, 3]]                   →  0

Hints

  1. Equivalently: keep the maximum number of non-overlapping intervals.
  2. Among intervals that could come next, keeping the one that ends earliest leaves the most room.
  3. Sort by end.

Approach

Sort by end time. Greedily keep an interval if its start ≥ the end of the last kept one; otherwise it overlaps, so count it as removed. Exchange argument: any optimal solution's first interval can be swapped for the earliest-ending one without causing conflicts, so the greedy choice is always safe. This is the classic activity-selection problem.

Complexity

Time: O(n log n). Space: O(1) extra.

Python solution
def eraseOverlapIntervals(intervals):
    intervals.sort(key=lambda x: x[1])
    removed, end = 0, float('-inf')
    for s, e in intervals:
        if s >= end:
            end = e
        else:
            removed += 1
    return removed
JavaScript solution
function eraseOverlapIntervals(intervals) {
  intervals.sort((a, b) => a[1] - b[1]);
  let removed = 0, end = -Infinity;
  for (const [s, e] of intervals) {
    if (s >= end) end = e; else removed++;
  }
  return removed;
}