Non-overlapping Intervals

MediumIntervals

You get a list of intervals, each [start, end]. Return the fewest intervals you must remove so that none of the remaining ones overlap.

Intervals that only touch, like [1, 3] and [3, 4], do not overlap.

Examples

Example 1
Input:  intervals = [[1, 3], [2, 5], [3, 4], [5, 6]]
Output: 1

Removing [2, 5] leaves [1, 3], [3, 4] and [5, 6], which only touch.

Example 2
Input:  intervals = [[4, 8], [4, 8], [4, 8]]
Output: 2

Three copies of one interval: keep one, remove two.

Constraints

  • 1 ≤ intervals.length ≤ 10⁵
  • -5 × 10⁴ ≤ start < end ≤ 5 × 10⁴

Stuck?

Hint 1

Count the most intervals you can keep instead. Among intervals that clash, keeping the one that ends first always leaves the most room.

Hint 2

Sort by end. Walk through, keeping an interval when it starts at or after the end of the last one kept, and counting it as removed otherwise.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 10 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur