Non-overlapping Intervals

You are given a list intervals, where each element [start, end] describes a stretch of the number line with start < end.

Return the smallest number of intervals you must delete so that no two of the remaining intervals overlap.

Two intervals overlap when they share some stretch of positive length. Intervals that only meet at a single point, such as [2, 5] and [5, 9], do not overlap. The input is not necessarily sorted, and identical intervals may appear more than once.

Example 1

Input: intervals = [[1,4],[2,3],[3,6],[5,7]] Output: 2 Why: For example, keep [2, 3] and [3, 6] (they only touch at 3) and delete [1, 4] and [5, 7]. No choice of three intervals is free of overlaps.

Example 2

Input: intervals = [[4,6],[0,2],[2,4]] Output: 0 Why: Sorted, the intervals are [0, 2], [2, 4], [4, 6]. Neighbours only touch at endpoints, so nothing needs to be deleted.

Example 3

Input: intervals = [[3,5],[3,5],[3,5]] Output: 2 Why: The three copies of [3, 5] all overlap each other, so only one can stay.

Constraints

  • 1 <= intervals.length <= 105
  • intervals[i].length == 2
  • -5 · 104 <= start < end <= 5 · 104

Pattern Path · Intervals & Greedy · problem 117 of 169

Turn the question around: what is the largest number of intervals you can keep with no overlaps?
If you had to choose the first interval to keep, which one leaves the most room for the others?
Sort by end point. Keep an interval whenever its start is at or after the end of the last kept interval.
Target: O(n log n) time, O(1) extra (besides sorting) extra space.

Start simple

Try every subset of intervals and keep the largest one with no overlaps: O(2ⁿ · n) time; a DP over intervals sorted by start still takes O(n²).

The key idea

Deleting as few intervals as possible is the same as keeping as many non-overlapping intervals as possible, so count the kept ones and subtract from n.

Sort the intervals by their end. Walk through them, remembering the end of the last interval you kept. If the current interval starts at or after that end, keep it and update the end. Otherwise it collides, and you delete it.

Why the earliest end is safe: take any optimal selection and look at its first interval. Swapping it for the interval that ends earliest overall cannot create a conflict, because that interval finishes no later, so everything after it still fits. Repeating the argument for each later choice shows the greedy selection is as large as any optimal one.

Sorting by start does not work on its own: a long interval that starts first, like [1, 100], would block many short ones. Ending early is what leaves the most room for the rest.

Complexity

  • Time: O(n log n)
  • Space: O(1) extra (besides sorting)

Python

class Solution:
    def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
        intervals.sort(key=lambda iv: iv[1])
        kept = 0
        last_end = float("-inf")
        for start, end in intervals:
            # Keep every interval that fits after the last one we kept.
            if start >= last_end:
                kept += 1
                last_end = end
        return len(intervals) - kept

JavaScript

var eraseOverlapIntervals = function(intervals) {
  intervals.sort((a, b) => a[1] - b[1]);
  let kept = 0;
  let lastEnd = -Infinity;
  for (const [start, end] of intervals) {
    // Keep every interval that fits after the last one we kept.
    if (start >= lastEnd) {
      kept++;
      lastEnd = end;
    }
  }
  return intervals.length - kept;
};

What the interviewer is checking

This tests whether you recognise the classic activity-selection greedy and can justify why sorting by end time, not start time, gives an optimal answer.

Mistakes to avoid

  • Treating intervals that only touch, like [1, 3] and [3, 5], as overlapping (use start >= lastEnd).
  • Sorting by start and always keeping the earlier interval, which keeps a long interval that blocks many short ones.
  • Starting lastEnd at 0, which wrongly rejects intervals with negative coordinates.

Follow-ups to expect

  • Return which intervals to delete, not just how many. (Record rejected intervals during the scan.)
  • How many meeting rooms do these intervals need? (Sweep starts and ends with a heap.)
  • What if each interval has a weight to maximise? (DP with binary search.)

In real software

Booking systems and schedulers use this to fit the most bookings into one room, machine or broadcast slot when requests overlap.

Practice next

Next Post Previous Post
No Comment
Add Comment
comment url