Non-overlapping Intervals

Medium Intervals AI round

intervals is a list of intervals, each [start, end] with start < end, in no particular order.

Two intervals overlap when one starts before the other ends. An interval that starts exactly where another ends does not overlap it: the two only meet.

Return the fewest intervals you have to remove so that no two of the ones left overlap.

Example 1

Input: intervals = [[5,9],[1,4],[3,6],[8,12],[11,13]]
Output: 2

Removing [3, 6] and [8, 12] leaves [1, 4], [5, 9] and [11, 13], and no two of those overlap. Removing one is not enough: whichever one goes, two of the four left still overlap.

Example 2

Input: intervals = [[10,15],[0,5],[5,10]]
Output: 0

[0, 5] and [5, 10] only meet at 5, and [5, 10] and [10, 15] only meet at 10, so nothing overlaps and nothing has to go.

Example 3

Input: intervals = [[-4,8],[-3,-1],[0,2],[3,5]]
Output: 1

Constraints

  • 1 ≤ intervals.length ≤ 10⁵
  • intervals[i] = [start, end]
  • -10⁹ ≤ start < end ≤ 10⁹

Watch the explanation

More Intervals

All Intervals problems