LeetCode #435 Medium

Non-overlapping Intervals

Non-overlapping Intervals is LeetCode 435 (Medium). Given a list of intervals [start, end], return the fewest intervals you must remove so that none of the remaining ones overlap.

  • Intervals that only touch, like [1, 2] and [2, 3], do not overlap.
  • There can be 10⁵ intervals, so trying different subsets is out of the question. One sort and one pass are enough.
Constraints
  • 1 <= intervals.length <= 10⁵
  • intervals[i].length == 2
  • -5 × 10⁴ <= startᵢ < endᵢ <= 5 × 10⁴
intervalsgreedysorting
Open on LeetCode ↗
02

Intuition

Removing the fewest intervals is the same as keeping the most: the answer is n minus the size of the largest set with no overlaps.

To keep the most, always keep the interval that ends first among those that still fit. This is safe. Take any best set and look at its earliest interval. Swap it for the interval with the earliest end overall: that one ends no later, so it cannot clash with anything else in the set, and the set is still valid and just as large. The same argument then applies to everything after it. An early end leaves the most room for the rest.

How to spot this pattern

"Remove the fewest" or "keep the most" intervals so none overlap is interval scheduling. Sorting by end time and taking whatever fits is the standard greedy for it.

03

Approach

Try it first

Before reading on, decide which interval you would keep first if you could keep only intervals that do not clash. Try both the earliest start and the earliest end on a long interval with three short ones inside it. Aim for O(n log n).

1

Sort by end

Sort the intervals by their end value. Among intervals with the same end, it does not matter which comes first: whichever one is kept blocks the future in exactly the same way.

2

Remember where the last kept interval ends

Keep end, the end of the last interval kept, starting at minus infinity so that the first interval is always kept. Count removals in removed.

3

Keep an interval that starts at or after end

If start >= end, the interval fits after everything kept so far. Keep it and move end to its end. The comparison is >= because touching intervals do not overlap.

4

Otherwise remove it

If it starts before end, it clashes with the last kept interval. It also ends no earlier, since the list is sorted by end, so keeping it instead could only leave less room. Remove it and leave end where it is.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def eraseOverlapIntervals(self, intervals: list[list[int]]) -> int:
▶3 intervals.sort(key=lambda iv: iv[1])
▶4 removed = 0
▶5 end = float("-inf")
▶6 for start, finish in intervals:
▶7 if start >= end:
▶8 end = finish
▶9 else:
▶10 removed += 1
▶11 return removed
input order1234intervals1–22–33–41–3last end−∞removed0first, sort the intervals by end
intervals4
The arcs are the intervals as given. Sorting by end puts the interval that frees up the line soonest first, which is the one worth keeping.
sorted by end1234intervals1–22–31–33–4last end−∞removed0nothing kept yet, so anything fits
end−∞
removed0
Now the tiles are in order of end. The last end starts at minus infinity, so the first interval is always kept.
sorted by end1234intervals1–22–31–33–4last end2removed0keep 1–2, the line is now busy until 2
start1
end2
1–2 has the earliest end of all, so keeping it leaves the most room for the rest.
sorted by end1234intervals1–22–31–33–4last end3removed0keep 2–3, the line is now busy until 3
start2
end3
2–3 starts at 2, exactly where the last kept interval ends; touching is allowed. It fits, so keep it and move the last end to 3.
sorted by end1234intervals1–22–31–33–4last end3removed11–3 starts before 3 → remove it
start1
removed1
1–3 starts at 1, before the last kept interval ends at 3, so the two clash. It ends no earlier (the list is sorted by end), so it is the one to remove, and the last end stays at 3.
sorted by end1234intervals1–22–31–33–4last end4removed1keep 3–4, the line is now busy until 4
start3
end4
3–4 starts at 3, exactly where the last kept interval ends; touching is allowed. It fits, so keep it and move the last end to 4.
sorted by end1234intervals1–22–31–33–4last end4removed1answer: remove 1
return1
The solid arcs are the largest set that fits together, 3 of 4. Everything else had to go, so the answer is 1.
05

Common pitfalls

Sorting by start and keeping the first one

✗ Wrong
intervals.sort()
✓ Right
intervals.sort(key=lambda iv: iv[1])

Sorted by start, a long interval that starts early is kept and blocks everything inside it. For [[1, 11], [2, 3], [4, 5], [6, 7]] that removes the three short intervals (3), while removing only [1, 11] is enough (1).

Treating touching intervals as overlapping

✗ Wrong
if start > end:
✓ Right
if start >= end:

For [[1, 2], [2, 3]] the strict test removes [2, 3] and returns 1, but intervals that share only an endpoint are allowed together, so the answer is 0.

Moving end when an interval is removed

✗ Wrong
else:
    removed += 1
    end = finish
✓ Right
else:
    removed += 1

A removed interval no longer takes up space. For [[1, 3], [2, 4], [3, 5]], moving end to 4 after removing [2, 4] makes [3, 5] look like a clash, giving 2 instead of 1.

06

Edge cases

Negative coordinates

Starts can go down to −5 × 10⁴. Starting end at 0 would remove [-5, -1] for no reason, so it starts at minus infinity (INT_MIN in C++, Integer.MIN_VALUE in Java).

07

Complexity

Time
O(n log n)
Space
O(log n)
The sort costs O(n log n) and the pass after it is O(n). Apart from the sort's own working space, only two numbers are kept.
08

Non-overlapping Intervals FAQ

Can I sort by start time instead?

Yes, if on every clash you keep the one of the two that ends sooner: count a removal and set end = min(end, finish). Sorting by end makes that choice automatic, so the loop has one less thing to get right.

Is this the activity selection problem?

Yes. N Meetings in One Room asks for the number of meetings you can keep; here you report how many are left out, which is n minus that number.

How does it relate to Minimum Number of Arrows to Burst Balloons?

That problem uses the same sort by end. There, balloons that touch can share one arrow, so the test becomes strictly greater and you count groups instead of removals.