Non-overlapping Intervals (LeetCode 435): Solution and Explanation
Given a list of intervals, return the smallest number of intervals you must remove so that none of the remaining ones overlap. Intervals that only touch at an endpoint, such as [1,2] and [2,3], do not count as overlapping.
Watch it run step by step
Try your own input and write the code →Intuition
Minimizing removals is the same as maximizing the number of intervals you keep. That reframing turns this into the classic activity selection problem: choose as many non-overlapping intervals as possible. Trying every subset is exponential, and even a DP over sorted intervals is O(n²), so it is worth asking whether a greedy choice is safe.
Think about which interval should be the first one you keep. Whatever you pick, everything that starts before it ends is blocked. So the best first choice is the interval that ends earliest, because it leaves the most room for everything after it. Any optimal solution can swap its first interval for the earliest-ending one without losing anything, since the replacement ends no later. Repeat the same argument for the rest of the timeline.
That gives a simple scan. Sort by end time, keep track of the end of the last interval you kept, and walk through the list. If an interval starts at or after that end, keep it and move the end forward. If it starts earlier, it overlaps something already kept, and since the kept one ends no later, discarding the new one is never worse. Count the discards and you have the answer.
Approach: Greedy by earliest end time
- Sort the intervals by their end value.
- Set
res = 0for the removal count andprevEndto negative infinity. - For each interval
(start, end)in sorted order, check whetherstart >= prevEnd. - If it does, the interval fits after the last kept one, so keep it and set
prevEnd = end. - Otherwise it overlaps, so increment
resand leaveprevEndunchanged. - Return
res.
Step-by-step example
intervals = [[1,2],[2,3],[3,4],[1,3]]
- Sorting by end gives [[1,2],[2,3],[1,3],[3,4]]. The stable sort keeps [2,3] ahead of [1,3] because both end at 3.
- [1,2] starts after negative infinity, so keep it and set
prevEndto 2. - [2,3] starts at 2, which is not before 2, so keep it and set
prevEndto 3. - [1,3] starts at 1, which is before 3, so remove it and
resbecomes 1. - [3,4] starts at 3, so keep it and set
prevEndto 4. Three intervals survive and one was removed, so the answer is 1.
Code: Python, Java, C++
1class Solution:
2 def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
3 intervals.sort(key = lambda x: x[1])
4
5 res = 0
6 prevEnd = float("-inf")
7
8 for start, end in intervals:
9 if start >= prevEnd:
10 prevEnd = end
11 else:
12 res += 1
13 return res1class Solution {
2 public int eraseOverlapIntervals(int[][] intervals) {
3 Arrays.sort(intervals, (a, b) -> Integer.compare(a[1], b[1]));
4
5 int res = 0;
6 int prevEnd = Integer.MIN_VALUE;
7
8 for (int[] interval : intervals) {
9 if (interval[0] >= prevEnd) {
10 prevEnd = interval[1];
11 } else {
12 res++;
13 }
14 }
15 return res;
16 }
17}1class Solution {
2public:
3 int eraseOverlapIntervals(vector<vector<int>>& intervals) {
4 sort(intervals.begin(), intervals.end(), [](const auto& a, const auto& b) {
5 return a[1] < b[1];
6 });
7
8 int res = 0;
9 int prevEnd = INT_MIN;
10
11 for (const auto& interval : intervals) {
12 if (interval[0] >= prevEnd) {
13 prevEnd = interval[1];
14 } else {
15 res++;
16 }
17 }
18 return res;
19 }
20};Time and space complexity
O(n log n)
Sorting dominates. The scan afterward is a single O(n) pass with constant work per interval, so the total stays O(n log n) even for very large inputs.
O(1)
Beyond the sort, which runs in place on the input (Python's sort may use up to O(n) temporary memory internally), the scan uses only two variables.
Other approaches
Sort by start and keep the smaller end (time O(n log n), space O(1))
Sort by start time. When the current interval overlaps the previous kept one, count a removal and keep whichever of the two ends earlier by setting prevEnd = min(prevEnd, end). It reaches the same answer with a slightly different update rule.
DP on longest chain (time O(n²), space O(n))
Sort by start, then compute for each interval the longest chain of compatible intervals ending there, like a longest increasing subsequence. The answer is n minus the best chain. It is correct but quadratic and too slow for large inputs.
Common mistakes
- Sorting by start time but always keeping the first interval of an overlapping pair. Without taking the smaller end, a long interval can block many short ones.
- Treating touching intervals as overlapping. The check must be
start >= prevEnd, notstart > prevEnd. - Updating
prevEndwhen an interval is removed. The removed interval no longer occupies the timeline. - Initializing
prevEndto 0, which wrongly removes intervals with negative start values.
Frequently asked questions
Why sort by end time for Non-overlapping Intervals?
Keeping the interval that ends earliest leaves the most room for later intervals. An exchange argument shows any optimal solution can be adjusted to start with that interval, so the greedy choice is always safe.
Is this the same as the activity selection problem?
Yes. Activity selection maximizes the number of compatible intervals, and the minimum removals equal the total count minus that maximum. The greedy end-time scan solves both.
Do intervals that share an endpoint overlap?
No. In this problem [1,2] and [2,3] can both be kept, which is why the comparison is start >= prevEnd.
How is this related to Minimum Number of Arrows to Burst Balloons?
Both sort by end and greedily keep the earliest finisher. The arrows problem counts groups of overlapping intervals rather than removals, and there touching intervals do count as overlapping, so the comparison becomes strict.