☰ All problems

61. Non-overlapping Intervals

You are given an array of intervals intervals, where intervals[i] = [start, end] and start < end.

Return the minimum number of intervals to delete so that no two of the remaining intervals overlap.

Two intervals that only share an endpoint, such as [1,2] and [2,3], do not overlap.

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

Explanation: Delete [2,4]; [1,3] and [3,5] only touch.

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

Explanation: Identical intervals overlap, so only one copy can stay.

Example 3
Input: intervals = [[1,2],[2,3]]
Output: 0

Constraints

  • 1 <= intervals.length <= 10^5
  • intervals[i].length == 2
  • -5 * 10^4 <= start < end <= 5 * 10^4

Follow-up: Why does sorting by start (and keeping the earliest-starting interval) fail? Find a small counterexample.

💡 Hint 1

Deleting as few as possible is the same as keeping as many non-overlapping intervals as possible.

💡 Hint 2

Among intervals that could come next, which one leaves the most room for the rest? The one that ends earliest.

💡 Hint 3

Sort by end. Keep an interval whenever its start is at or after the end of the last kept one; otherwise it has to go.

/**
 * @param {number[][]} intervals
 * @return {number}
 */
function eraseOverlapIntervals(intervals) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc