435. Non Overlapping Intervals - Explanation
Description
Given an array of intervals intervals where intervals[i] = [start_i, end_i], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Note: Intervals are non-overlapping even if they have a common point. For example, [1, 3] and [2, 4] are overlapping, but [1, 2] and [2, 3] are non-overlapping.
Example 1:
Input: intervals = [[1,2],[2,4],[1,4]]
Output: 1Explanation: After [1,4] is removed, the rest of the intervals are non-overlapping.
Example 2:
Input: intervals = [[1,2],[2,4]]
Output: 0Constraints:
1 <= intervals.length <= 100,000intervals[i].length == 2-50000 <= starti < endi <= 50000
Topics
Recommended Time & Space Complexity
You should aim for a solution with O(nlogn) time and O(n) space, where n is the size of the input array.
Hint 1
If two intervals are sorted in ascending order by their start values, they overlap if the start value of the second interval is less than the end value of the first interval. And these are called overlapping intervals.
Hint 2
A brute force approach would be to sort the given intervals in ascending order based on their start values and recursively explore all possibilities. This would be an exponential approach. Can you think of a better way? Maybe a greedy approach works here.
Hint 3
We first sort the given intervals based on their start values to efficiently check for overlaps by comparing adjacent intervals. We then iterate through the sorted intervals from left to right, keeping track of the previous interval’s end value as prevEnd, initially set to the end value of the first interval.
Hint 4
We then iterate from the second interval. If the current interval doesn't overlap, we update prevEnd to the current interval's end and continue. Otherwise, we set prevEnd to the minimum of prevEnd and the current interval’s end, greedily removing the interval that ends last to retain as many intervals as possible.
Prerequisites
Before attempting this problem, you should be comfortable with:
- Sorting - Sorting intervals by start or end time to enable efficient processing
- Greedy algorithms - Selecting intervals that leave maximum room for future choices
- Dynamic Programming - Using memoization or tabulation to count optimal non-overlapping intervals
- Binary Search - Finding the last non-overlapping interval efficiently in optimized DP solutions
1. Recursion
Intuition
We want to remove the minimum number of intervals so that the remaining intervals do not overlap.
A helpful way to think about this is:
- instead of directly counting removals, we can try to keep as many non-overlapping intervals as possible
- if we know the maximum number of intervals we can keep without overlap, then:
minimum removals = total intervals - maximum kept
To make decisions, we sort the intervals by start time and use recursion to explore two choices at each interval:
- Skip the current interval
- Take the current interval (only if it does not overlap with the previously taken interval)
The recursive function represents:
"What is the maximum number of non-overlapping intervals we can keep starting from index i, given that the last chosen interval is prev?"
Algorithm
- Sort the intervals by their start time.
- Define a recursive function
dfs(i, prev):iis the current interval indexprevis the index of the last chosen interval (-1if none chosen yet)
- Base case:
- If
ireaches the end of the list, return0(no more intervals to take)
- If
- Option 1: Skip the current interval:
res = dfs(i + 1, prev)
- Option 2: Take the current interval (only if it doesn't overlap):
- If
prev == -1orintervals[prev][1] <= intervals[i][0]:res = max(res, 1 + dfs(i + 1, i))
- If
- Return
res, the maximum number of intervals we can keep from this state. - Compute
kept = dfs(0, -1) - Return
len(intervals) - keptas the minimum number of intervals to remove.
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
intervals.sort()
def dfs(i, prev):
if i == len(intervals):
return 0
res = dfs(i + 1, prev)
if prev == -1 or intervals[prev][1] <= intervals[i][0]:
res = max(res, 1 + dfs(i + 1, i))
return res
return len(intervals) - dfs(0, -1)Time & Space Complexity
- Time complexity:
- Space complexity:
2. Dynamic Programming (Top-Down)
Intuition
We want to remove the minimum number of intervals so that the remaining intervals do not overlap.
A common trick is to flip the problem:
- instead of counting removals directly, find the maximum number of non-overlapping intervals we can keep
- then:
minimum removals = total intervals - maximum kept
This solution sorts intervals by end time. After that, for any interval i, the next interval we choose must start at or after intervals[i][1].
We define a DP state that answers:
"If we choose interval i as part of our set, what is the maximum number of non-overlapping intervals we can take starting from i?"
The result for an index depends on future indices, and many states repeat, so we use memoization.
Algorithm
- Sort the intervals by their end time.
- Let
nbe the number of intervals. - Use a memo map
memoto store results for each indexi. - Define a recursive function
dfs(i):- returns the maximum number of non-overlapping intervals we can take
starting with intervaliincluded
- returns the maximum number of non-overlapping intervals we can take
- If
iis already inmemo, return the stored value. - Initialize
res = 1because we are taking intervali. - Try to extend the chain by choosing a next interval
jwherej > i:- only valid if
intervals[i][1] <= intervals[j][0] - if valid, update:
res = max(res, 1 + dfs(j))
- only valid if
- Store
resinmemo[i]and return it. - The maximum kept intervals is computed as
dfs(0). - Return
n - dfs(0)as the minimum number of intervals to remove.
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
intervals.sort(key = lambda x: x[1])
n = len(intervals)
memo = {}
def dfs(i):
if i in memo:
return memo[i]
res = 1
for j in range(i + 1, n):
if intervals[i][1] <= intervals[j][0]:
res = max(res, 1 + dfs(j))
memo[i] = res
return res
return n - dfs(0)Time & Space Complexity
- Time complexity:
- Space complexity:
3. Dynamic Programming (Bottom-Up)
Intuition
We want to remove the minimum number of intervals so that the remaining intervals do not overlap.
A useful trick is to instead find the maximum number of non-overlapping intervals we can keep.
Once we know that:
minimum removals = total intervals - maximum kept
After sorting intervals by end time, we can build a DP array where:
dp[i]= the maximum number of non-overlapping intervals we can keep ending at intervali(meaning intervaliis included)
To compute dp[i], we look at all earlier intervals j < i:
- if interval
jends before intervalistarts, they can both be kept - so we can extend the chain:
1 + dp[j]
Algorithm
- Sort the intervals by their end time.
- Let
nbe the number of intervals. - Create an array
dpof sizen. - For each interval index
ifrom0ton - 1:- Start with
dp[i] = 1(we can always keep intervalialone) - For every earlier interval
jfrom0toi - 1:- If
intervals[j][1] <= intervals[i][0]:- update
dp[i] = max(dp[i], 1 + dp[j])
- update
- If
- Start with
- After filling
dp, the maximum number of non-overlapping intervals we can keep is:max_non_overlapping = max(dp)
- Return the minimum removals:
n - max_non_overlapping
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
intervals.sort(key=lambda x: x[1])
n = len(intervals)
dp = [0] * n
for i in range(n):
dp[i] = 1
for j in range(i):
if intervals[j][1] <= intervals[i][0]:
dp[i] = max(dp[i], 1 + dp[j])
max_non_overlapping = max(dp)
return n - max_non_overlappingTime & Space Complexity
- Time complexity:
- Space complexity:
4. Dynamic Programming (Binary Search)
Intuition
We want to remove the minimum number of intervals so that the remaining intervals do not overlap.
A common trick is to flip the goal:
- instead of counting removals directly, find the maximum number of non-overlapping intervals we can keep
- then:
minimum removals = total intervals - maximum kept
After sorting intervals by end time, consider interval i:
- we have two choices:
- skip interval
i→ keep the best answer up toi - 1 - take interval
i→ then we must take it after the last interval that ends
beforeintervals[i][0]
- skip interval
The slow part is finding that "previous compatible interval".
Because the intervals are sorted by end time, we can find it using binary search.
We maintain:
dp[i]= maximum number of non-overlapping intervals we can keep using intervals0..i
Algorithm
- Sort the intervals by their end time.
- Create a DP array
dpof sizen:dp[i]stores the maximum number of non-overlapping intervals we can keep
among the firsti + 1intervals
- Set
dp[0] = 1since we can always keep the first interval. - For each interval
ifrom1ton - 1: - Use binary search to find
idx:- the first position in
[0, i)whereintervals[pos][1] > intervals[i][0] - so
idx - 1is the last interval that does not overlap with intervali
- the first position in
- Update
dp[i]:- If no compatible interval exists (
idx == 0):- we can only take interval
ialone, so compare with skipping:dp[i] = dp[i - 1]
- we can only take interval
- Otherwise:
- Option 1: skip interval
i→dp[i - 1] - Option 2: take interval
i→1 + dp[idx - 1] dp[i] = max(dp[i - 1], 1 + dp[idx - 1])
- Option 1: skip interval
- If no compatible interval exists (
- After filling DP, the maximum kept is
dp[n - 1]. - Return
n - dp[n - 1]as the minimum number of intervals to remove.
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
intervals.sort(key=lambda x: x[1])
n = len(intervals)
dp = [0] * n
dp[0] = 1
def bs(r, target):
l = 0
while l < r:
m = (l + r) >> 1
if intervals[m][1] <= target:
l = m + 1
else:
r = m
return l
for i in range(1, n):
idx = bs(i, intervals[i][0])
if idx == 0:
dp[i] = dp[i - 1]
else:
dp[i] = max(dp[i - 1], 1 + dp[idx - 1])
return n - dp[n - 1]Time & Space Complexity
- Time complexity:
- Space complexity:
5. Greedy (Sort By Start)
Intuition
We want to remove the minimum number of intervals so that the remaining intervals do not overlap.
A greedy strategy works well here. After sorting intervals by their start time, we process them from left to right and always keep the interval that ends earlier when an overlap occurs.
Why this works:
- When two intervals overlap, keeping the one with the smaller end time leaves more room for future intervals
- Removing the interval with the larger end is always the better choice, because keeping it would block more upcoming intervals
So instead of choosing which interval to keep globally, we make a local greedy decision whenever an overlap happens.
Algorithm
- Sort the intervals by their start time.
- Initialize:
prevEndas the end of the first intervalres = 0to count how many intervals we remove
- Iterate through the remaining intervals one by one:
- For each interval
(start, end):- If
start >= prevEnd:- There is no overlap
- Update
prevEnd = end
- Else (overlap exists):
- We must remove one interval
- Increment
res - Keep the interval with the smaller end:
prevEnd = min(end, prevEnd)
- If
- After processing all intervals, return
res
Time & Space Complexity
- Time complexity:
- Space complexity: or depending on the sorting algorithm.
6. Greedy (Sort By End)
Intuition
We want to remove the minimum number of intervals so that the remaining intervals do not overlap.
A very clean greedy idea is to always keep the interval that ends earliest.
Why? Because an interval that ends earlier leaves more room for future intervals, reducing the chance of overlap later.
So instead of deciding which intervals to remove directly, we:
- sort all intervals by their end time
- walk through them from left to right
- keep track of the end of the last interval we decided to keep
Whenever we see an overlap:
- we remove the current interval
- because it ends later than the one we already kept (due to sorting)
This greedy choice is optimal and ensures the maximum number of intervals are kept.
Algorithm
- Sort all intervals by their end time.
- Initialize:
prevEndas the end of the first intervalres = 0to count how many intervals we remove
- Iterate through the intervals starting from the second one:
- For each interval
(start, end):- If
start < prevEnd:- The interval overlaps with the previous one
- Remove this interval → increment
res
- Else:
- No overlap
- Update
prevEnd = end
- If
- After processing all intervals, return
res
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
intervals.sort(key = lambda pair: pair[1])
prevEnd = intervals[0][1]
res = 0
for i in range(1, len(intervals)):
if prevEnd > intervals[i][0]:
res += 1
else:
prevEnd = intervals[i][1]
return resTime & Space Complexity
- Time complexity:
- Space complexity: or depending on the sorting algorithm.
Common Pitfalls
Sorting by the Wrong Criterion
Sorting by start time instead of end time (or vice versa without proper handling) leads to suboptimal solutions. While both can work, sorting by end time gives a cleaner greedy solution because the interval that ends earliest always leaves the most room for future intervals. Sorting by start time requires additional logic to handle overlaps correctly.
Incorrect Overlap Detection
Using < instead of <= (or vice versa) when checking for overlaps causes off-by-one errors. Intervals [1, 2] and [2, 3] do NOT overlap because one ends exactly where the other begins. The condition should be intervals[i][0] >= prevEnd for non-overlapping, not intervals[i][0] > prevEnd.
Counting Kept Intervals Instead of Removed
Confusing what to count leads to returning the wrong answer. The problem asks for the minimum number of intervals to REMOVE, not the maximum to keep. If you count intervals kept, remember to return n - kept as the final answer. This subtle difference causes many incorrect submissions.
Sign in to join the discussion