Skip to content
Problem 435 · LeetCode 435(opens in a new tab)

Non-overlapping Intervals

MediumGreedy algorithms

You are given a list of intervals, where each one is a pair [start, end] with start below end. Two intervals overlap when they share more than a single point; intervals that only touch, like [2, 5] and [5, 8], do not overlap.

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

Example 1

Input:  intervals = [[1,4], [2,3], [3,6], [5,7]]
Output: 2
Why:    keep [2,3] and [3,6]; [1,4] and [5,7] each clash with one
2 more examples and the constraints

Example 2

Input:  intervals = [[-2,1], [1,4], [4,8]]
Output: 0
Why:    each one only touches the next, so nothing overlaps

Example 3

Input:  intervals = [[3,5], [3,5], [0,10]]
Output: 2
Why:    only one interval can stay; all three overlap

Constraints

  • 1 ≤ number of intervals ≤ 100,000
  • Each interval has exactly two numbers, start and end
  • −50,000 ≤ start < end ≤ 50,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. DP on the longest chainO(n²)
  2. Greedy by earliest endO(n log n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 intervalsVerdict
DP on the longest chainO(n²)
Correct; too slow
Greedy by earliest endO(n log n)
Best; sort and one pass

n = number of intervals.

Edge cases to test

  • Touching ends. [1, 3] and [3, 5] do not overlap. Compare with >=, not >.
  • Exact duplicates. [[3, 5], [3, 5]] keeps one copy and removes the other.
  • One long interval over short ones. [[1, 10], [2, 3], [4, 5], [6, 7]] removes the long one, not the three short ones.
  • A single interval. Nothing can overlap it, so the answer is 0.
  • Negative coordinates. Starts can be as low as −50,000, so end must start below every value, not at 0.

Common mistakes

  • Sorting by start and keeping whichever comes first, which keeps long intervals that block many short ones.
  • Treating touching intervals as overlapping by comparing with > instead of >=.
  • Starting end at 0, which wrongly removes intervals that start at a negative number.

How to talk through it

  1. 1Clarify. Do touching intervals overlap? Can the list contain duplicates or negative numbers?
  2. 2Reframe it. Removing the fewest is keeping the most clash-free intervals.
  3. 3Give the DP. Longest chain ending at each interval, O(n²). Correct, but too slow for 100,000.
  4. 4Argue the greedy. Keep the interval that ends first; it leaves the most room, so an exchange argument shows it is safe.
  5. 5Test out loud. Run the touching case, the duplicates and the long-over-short case.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?