Skip to main content
66

Non-overlapping Intervals

Mediumintervalsgreedy

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:IntervalsRead the beginner guide

Given an array of intervals, return the minimum number of intervals to remove so that the remaining ones don't overlap.

Understand the problem

  • An interval [start, end] covers the time from start up to end.
  • Two intervals overlap if one starts before the other ends. Intervals that only touch, like [1, 2] and [2, 3], do not overlap.
  • You remove some intervals so that the rest don't overlap at all, and you want to remove as few as possible.
  • You return how many to remove, not which ones.

Example 1

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

Remove [1, 3]. The rest, [1, 2], [2, 3], [3, 4], only touch each other.

Example 2

text
Input:  intervals = [[1, 2], [1, 2], [1, 2]]
Output: 2

All three are the same, so only one can stay.

Example 3

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

They only touch: nothing to remove.

Constraints

  • 1 <= intervals.length <= 10^5
  • -5 * 10^4 <= start < end <= 5 * 10^4

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Sort the intervals by end time and keep every interval that starts after the last kept one ends; everything else is removed, and that count is the answer.

    The naive approach (and why it's slow)

    Try every subset of intervals to keep, check whether it's non-overlapping, and find the largest. There are 2^n subsets: impossible for 100,000 intervals.

    Flip the question

    Removing the fewest is the same as keeping the most non-overlapping intervals. This is a classic problem called activity selection: fit as many activities as possible into one room.

    The key insight: keep the one that ends earliest

    Which interval should you keep first? The one that ends earliest. It frees up the timeline soonest, leaving the most room for everything after it.

    Why is that safe? Take any best plan. Its first interval ends at some time t. Swap it for the earliest-ending interval: that one ends at or before t, so it can't clash with anything the plan keeps after. The plan is still valid and still the same size. The same argument then repeats for the next interval. (This is called an exchange argument.)

    So:

    1. Sort by end.
    2. Keep track of end, the end of the last interval you kept (start at -Infinity).
    3. For each interval: if start >= end, keep it and set end to its end. Otherwise, count it as removed.

    Step by step

    intervals = [[1, 2], [2, 3], [3, 4], [1, 3]]. Sorted by end: [1, 2], [2, 3], [1, 3], [3, 4].

    IntervalLast kept ends atStarts at or after it?ActionRemoved
    [1, 2]−∞yeskeep0
    [2, 3]22 >= 2: yeskeep0
    [1, 3]31 >= 3: noremove1
    [3, 4]33 >= 3: yeskeep1

    Answer: 1.

    Why not sort by start?

    Sorting by start feels natural, but it fails: in [[1, 100], [2, 3], [4, 5]], [1, 100] starts first. Keeping it blocks both others (2 removals), but removing just it keeps [2, 3] and [4, 5] (1 removal). Sorting by end picks [2, 3] and [4, 5] first, correctly.

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    • Time: O(n log n) for the sort.
    • Memory: O(n) for the sorted copy.

    Common mistakes

    • Sorting by start (see above).
    • Treating touching intervals as overlapping. Use start >= end to keep.
    • Counting the kept ones and returning that. The question asks for the number removed.

    Going deeper

    • This is the same idea as Meeting Rooms, turned into an optimization: instead of "is there any clash?", it's "how few do I remove so there's none?".
    • "Earliest end first" is one of the most famous greedy rules. Whenever a problem asks to fit the most non-overlapping intervals, try it.

    Reference solution

    js
    /**
     * @param {number[][]} intervals
     * @return {number}
     */
    export default function eraseOverlapIntervals(intervals) {
      // Earliest end first: it leaves the most room for everything after it.
      const sorted = [...intervals].sort((a, b) => a[1] - b[1])
      let removed = 0
      let end = -Infinity // end of the last interval we kept (none yet)
      for (const [start, finish] of sorted) {
        if (start >= end)
          end = finish // no clash (touching is fine): keep it
        else removed++ // overlaps the last kept one: remove it
      }
      return removed
    }
    ts
    export default function eraseOverlapIntervals(intervals: number[][]): number {
      // Earliest end first: it leaves the most room for everything after it.
      const sorted = [...intervals].sort((a, b) => a[1] - b[1])
      let removed = 0
      let end = -Infinity // end of the last interval we kept (none yet)
      for (const [start, finish] of sorted) {
        if (start >= end)
          end = finish // no clash (touching is fine): keep it
        else removed++ // overlaps the last kept one: remove it
      }
      return removed
    }
    python
    def erase_overlap_intervals(intervals: list[list[int]]) -> int:
        removed = 0
        end = float("-inf")  # end of the last interval we kept (none yet)
        # Earliest end first: it leaves the most room for everything after it.
        for start, finish in sorted(intervals, key=lambda interval: interval[1]):
            if start >= end:
                end = finish  # no clash (touching is fine): keep it
            else:
                removed += 1  # overlaps the last kept one: remove it
        return removed