MediumPythonJavaScriptTypeScript
Greedy — Non-overlapping Intervals
AlgorithmsGreedyIntervals
solve(intervals) — intervals[i] = [start, end]. Return the **minimum number of
intervals to remove** so that the rest do not overlap. Intervals that only touch
([1,2] and [2,3]) do not overlap.
Equivalently, keep the maximum number of compatible intervals. The classic
greedy choice: sort by end time and always keep the interval that ends earliest,
because it leaves the most room for the others.
Examples
solve([[1,2],[2,3],[3,4],[1,3]]) → 1
solve([[1,2],[1,2],[1,2]]) → 2
solve([[1,2],[2,3]]) → 0
solve([[1,100],[11,22],[1,11],[2,12]]) → 2
solve([]) → 0Sample tests
Test #1Classic example
Input: [[[1,2],[2,3],[3,4],[1,3]]]
Output: 1
Test #2Identical intervals
Input: [[[1,2],[1,2],[1,2]]]
Output: 2
Test #3Touching is not overlapping
Input: [[[1,2],[2,3]]]
Output: 0