Non-overlapping Intervals
1 approach, code in every language
Problem description
Given a set of intervals, figure out the smallest number of them you would need to delete so that the ones left behind never overlap. Intervals that only share an endpoint are considered compatible and do not need to be removed.
Return that minimum deletion count. This is equivalent to keeping the largest possible set of mutually compatible intervals and removing everything else.
Example 1
Input: intervals = [[1,2],[2,4],[1,4]]
Output: 1
Dropping [1,4] leaves [1,2] and [2,4], which only touch at 2 and so do not overlap.
Example 2
Input: intervals = [[1,3],[1,3],[1,3]]
Output: 2
All three cover the same span, so two of the duplicates must go.
Constraints
1 ≤ intervals.length ≤ 10^5intervals[i].length == 2-5 * 10^4 ≤ start < end ≤ 5 * 10^4
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Drop the Clashing Kiln Runs is our own problem on the technique behind Non-overlapping Intervals: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free