Example 1
- Input
- intervals = [[1,2],[2,3],[3,4],[1,3]]
- Output
- 1
Remove [1,3] and the remaining [1,2], [2,3], [3,4] are pairwise non-overlapping.
You are given a list of intervals and may delete any of them. Return the smallest number of deletions that leaves the remaining intervals pairwise non-overlapping.
Given a nonempty list intervals of positive-length intervals [start, end], remove the fewest intervals so the remaining ones are pairwise non-overlapping. Return the removal count, not the retained intervals.
Intervals sharing only an endpoint are compatible: [1,2] and [2,3] may both remain. Input order is arbitrary and endpoints may be negative. The implementations below preserve the original outer order and all row values.
Remove [1,3] and the remaining [1,2], [2,3], [3,4] are pairwise non-overlapping.
Keep any one copy of [1,2] and remove the other two.
The intervals only touch at 2, so nothing needs removing.
Remove the long interval [0,10] and keep all three short intervals. Keeping the earliest-starting interval instead would force three removals.
A single interval never conflicts with another. Negative endpoint values do not change the compatibility test.
Minimizing removals is equivalent to maximizing how many intervals we keep. In Example 1, keeping [1,2], [2,3], and [3,4] beats keeping the longer [1,3] with [3,4]. An interval ending sooner leaves at least as much room for every future choice. That suggests sorting by end and accepting compatible intervals, while exhaustive keep-or-drop choices provide a direct baseline for small inputs. Endpoint contact is allowed here, unlike closed-interval merging.
Reveal Exhaustive Subsets: intuition, complexity, and code
[1,2], need all but one removed.[[1,2],[2,3]] returns 0.[1,2] and [2,3] coexist.[[0,10],[1,2],[2,3],[3,4]] needs only one removal. Prefer earliest end.To keep the most intervals, always keep the one that ends first: sorting by end time makes that greedy choice available at every step.