loading

Non-overlapping Intervals — Step-by-Step Visualization

mediumLeetCode #435ArrayDynamic ProgrammingGreedySorting

Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.

Algorithm Pattern

Greedy (Sort by End Time)

Key Idea

Sort intervals by end time. Greedily keep each interval that doesn't overlap the previous kept one. Every overlap → one removal.

Step-by-Step Approach

  1. Sort intervals by end time.
  2. Track prevEnd = end of last kept interval.
  3. For each interval: if start >= prevEnd, keep it (update prevEnd).
  4. Otherwise it overlaps — remove it (res++).
  5. Return res.

Common Gotchas

  • Sort by END time, not start time.
  • When two intervals overlap, always discard the one with the larger end (so we keep more future room) — sorting by end ensures this automatically.

Related Problems