Non Overlapping Intervals
MediumNeetCode 150 IntervalsGrammarlyVerkadaProblem
Each element of intervals is a range [start, end]. Two ranges overlap when they share
more than a single point, so ranges that only touch at an endpoint do not overlap.
Return the smallest number of ranges you must remove so that the remaining ranges do not overlap each other.
Constraints
- 1 ≤ intervals.length ≤ 10⁵
- intervals[i].length == 2
- −5·10⁴ ≤ start < end ≤ 5·10⁴
Examples: pick one to animate
Solutions
TimeO(n log n)
SpaceO(1)
Time: Sorting costs O(n log n); the pass over the ranges is O(n).
Space: Only the removal count and the last kept end are stored (not counting the sort's own working space).
Sort by end. Keep the first range, since finishing earliest leaves the most room. Walk through the rest: if a range starts at or after the last kept end, keep it and move the end forward. Otherwise it overlaps the kept range, so remove it and count one removal.