15% off all plans & roadmaps Use code
See plansNon-overlapping Intervals
- LeetCode 435
- Medium
- Greedy Patterns
- Interval Merging/Scheduling
Updated
TL;DR: Find the largest set of intervals that do not overlap, then remove everything else. Sort by end point and greedily keep each interval that starts at or after the last kept end.
Problem
You are given an array intervals, where each intervals[i] = [start, end] describes one interval. Two intervals overlap when they share an interior portion. Intervals that only meet at an endpoint, such as [1,3] and [3,6], do not overlap.
Remove as few intervals as you can so that every pair of remaining intervals is non-overlapping. Return the minimum number of intervals you must remove.
Example 1
Input: intervals = [[1,3],[3,6],[6,10]] Output: 0 Explanation: Each interval only touches the next one at an endpoint, so none of them overlap.
Example 2
Input: intervals = [[1,4],[2,3],[5,7],[6,8]] Output: 2 Explanation: One interval must go from each overlapping pair. For instance, keep [2,3] and [5,7].
Example 3
Input: intervals = [[1,10],[2,4],[3,7],[8,9]] Output: 2 Explanation: [1,10] overlaps all three shorter intervals, and [2,4] overlaps [3,7]. Removing [1,10] and one of [2,4] or [3,7] leaves a non-overlapping set.
Constraints
1 <= intervals.length <= 10^5intervals[i].length == 2start < endfor every interval1 <= start <= 5 * 10^41 <= end <= 5 * 10^4
Constraints that matter
nup to 10^5 rules out any approach that tries subsets (2^n). It also rules out the O(n^2) pairwise DP, which needs about 10^10 steps.- An O(n log n) sort followed by one linear scan fits comfortably, so the answer is a sort plus a greedy pass.
start < endmeans every interval has positive length, so there are no zero-width intervals to special-case.- Coordinates are at most 5 * 10^4, so there is no integer overflow in any language. A sentinel such as 0 or a minimum integer is safe for the initial boundary.
- At least one interval is always present, so the list is never empty and a first interval always exists.
Hints
Hint 1
Removing the fewest intervals is the same as keeping the most intervals.
Hint 2
Treat it as a pure choice problem.
Solution
Intuition
Removing the fewest intervals is the same as keeping the most intervals. So the question becomes: what is the largest set of pairwise non-overlapping intervals? This is the interval scheduling problem, and the pattern is a greedy choice after sorting.
Picture one meeting room with a booking calendar. The variable lastEnd is the time the room next becomes free, and you book any meeting that starts at or after that time.
Think of the timeline as a single room where you want to book as many meetings as possible. The meeting that frees the room earliest leaves the most time for everything after it. That points to sorting by end point, not by start point.
Why does it work? Suppose two intervals both fit as the next pick, and one ends earlier. Anything that can follow the later-ending interval can also follow the earlier-ending one, because it only needs to start at or after a smaller number. Swapping in the earlier-ending interval never shrinks the final set, so you can always take it.
The overlap test is start < lastEnd. Equal values mean the intervals touch, which is legal, so the keep condition is start >= lastEnd.
Worked example
Input: intervals = [[1,3],[3,6],[6,10]] Output: 0 Explanation: Each interval starts exactly where the previous one ends. Touching at an endpoint is allowed, so all three intervals stay and nothing is removed.
Approach 1: Brute force: try keep or drop for every interval
Treat it as a pure choice problem. For each interval you either keep it or drop it, and you want the largest kept set that has no overlaps. Sort by start so you decide intervals left to right, and carry the end of the last kept interval. An interval can be kept only if its start is at or after that end.
This is correct because every subset is explored, but it is exponential.
Steps
- Sort the intervals by start.
- Define
best(i, prevEnd)as the largest number of intervals you can keep from indexionward, given the last kept interval ended atprevEnd. - If
iequalsn, return 0. - Compute the drop option:
best(i + 1, prevEnd). - If
intervals[i][0] >= prevEnd, compute the keep option:1 + best(i + 1, intervals[i][1]). - Return the larger of the two options.
- Answer
n - best(0, 0).
Dry run
Take [[1,3],[3,6],[6,10]], already sorted by start. Call best(0, 0).
- Interval
[1,3]: start 1 >= 0, so keeping is allowed. The callbest(1, 3)runs next. - Interval
[3,6]: start 3 >= 3, so keeping is allowed. The callbest(2, 6)runs next. - Interval
[6,10]: start 6 >= 6, so keep it.best(3, 10)returns 0, so this branch returns 1. - Going back up, the keep-everything branch yields 3. Drop branches yield at most 2.
The largest kept set is 3, so the answer is 3 - 3 = 0. The recursion visits up to 2^3 = 8 leaves here, but 2^100000 on a worst-case input.
Complexity
| Time | O(2^n) |
|---|---|
| Space | O(n) |
Here n is the number of intervals. Each interval has two choices, so the recursion tree has up to 2^n leaves. The recursion depth is n, so the call stack uses O(n) space. The sort adds only O(n log n) time, which is dominated.
PythonTested in our runner
from typing import List, Optional
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
intervals.sort()
n = len(intervals)
def best(i: int, prev_end: int) -> int:
if i == n:
return 0
res = best(i + 1, prev_end) # drop interval i
if intervals[i][0] >= prev_end: # keep interval i
res = max(res, 1 + best(i + 1, intervals[i][1]))
return res
return n - best(0, 0)
JavaTested in our runner
import java.util.*;
class Solution {
public int eraseOverlapIntervals(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
return intervals.length - best(intervals, 0, 0);
}
private int best(int[][] a, int i, int prevEnd) {
if (i == a.length) {
return 0;
}
int res = best(a, i + 1, prevEnd); // drop
if (a[i][0] >= prevEnd) {
res = Math.max(res, 1 + best(a, i + 1, a[i][1])); // keep
}
return res;
}
}
C++Tested in our runner
using namespace std;
class Solution {
public:
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end());
int n = intervals.size();
return n - best(intervals, 0, 0);
}
private:
int best(vector<vector<int>>& a, int i, int prevEnd) {
if (i == (int)a.size()) {
return 0;
}
int res = best(a, i + 1, prevEnd); // drop
if (a[i][0] >= prevEnd) {
res = max(res, 1 + best(a, i + 1, a[i][1])); // keep
}
return res;
}
};
JavaScriptTested in our runner
/**
* @param {number[][]} intervals
* @return {number}
*/
var eraseOverlapIntervals = function(intervals) {
intervals.sort((a, b) => a[0] - b[0]);
const n = intervals.length;
const best = (i, prevEnd) => {
if (i === n) {
return 0;
}
let res = best(i + 1, prevEnd); // drop
if (intervals[i][0] >= prevEnd) {
res = Math.max(res, 1 + best(i + 1, intervals[i][1])); // keep
}
return res;
};
return n - best(0, 0);
};
GoTested in our runner
import "sort"
func eraseOverlapIntervals(intervals [][]int) int {
sort.Slice(intervals, func(i, j int) bool {
return intervals[i][0] < intervals[j][0]
})
n := len(intervals)
var best func(i, prevEnd int) int
best = func(i, prevEnd int) int {
if i == n {
return 0
}
res := best(i+1, prevEnd) // drop
if intervals[i][0] >= prevEnd {
if keep := 1 + best(i+1, intervals[i][1]); keep > res {
res = keep
}
}
return res
}
return n - best(0, 0)
}
C#Tested in our runner
public class Solution {
public int eraseOverlapIntervals(int[][] intervals) {
Array.Sort(intervals, (a, b) => a[0].CompareTo(b[0]));
return intervals.Length - Best(intervals, 0, 0);
}
private int Best(int[][] a, int i, int prevEnd) {
if (i == a.Length) {
return 0;
}
int res = Best(a, i + 1, prevEnd); // drop
if (a[i][0] >= prevEnd) {
res = Math.Max(res, 1 + Best(a, i + 1, a[i][1])); // keep
}
return res;
}
}
Approach 2: Dynamic programming over sorted starts
What's slow: the recursion recomputes the same state many times. The answer for best(i, prevEnd) depends only on which interval was kept last, not on the path that led there. So there are only n distinct states that matter.
The insight that fixes it: define dp[i] as the largest non-overlapping chain that ends with interval i. After sorting by start, any earlier interval j can precede i when end_j <= start_i. Take the best such dp[j] and add one. This is the longest chain pattern.
Steps
- Sort the intervals by start.
- Create
dpof length n, filled with 1, since each interval alone is a chain of length 1. - For each
i, scan everyj < i. - If
intervals[j][1] <= intervals[i][0], setdp[i] = max(dp[i], dp[j] + 1). - Track the maximum
dp[i]askept. - Return
n - kept.
Dry run
On [[1,3],[3,6],[6,10]] sorted by start, dp starts as [1, 1, 1].
i = 1: checkj = 0. End 3 <= start 3, sodp[1] = dp[0] + 1 = 2.i = 2: checkj = 0. End 3 <= start 6, sodp[2] = 2. Checkj = 1. End 6 <= start 6, sodp[2] = dp[1] + 1 = 3.
The maximum is 3, so kept = 3 and the answer is 3 - 3 = 0.
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(n) |
Here n is the number of intervals. The nested loops compare each pair (j, i) with j < i once, which is n * (n - 1) / 2 comparisons. The dp array holds one integer per interval, so space is O(n). With n = 10^5 this is about 5 * 10^9 comparisons, too slow.
PythonTested in our runner
from typing import List, Optional
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
intervals.sort()
n = len(intervals)
dp = [1] * n # dp[i]: longest chain ending at interval i
kept = 1
for i in range(n):
for j in range(i):
if intervals[j][1] <= intervals[i][0]:
dp[i] = max(dp[i], dp[j] + 1)
kept = max(kept, dp[i])
return n - kept
JavaTested in our runner
import java.util.*;
class Solution {
public int eraseOverlapIntervals(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
int n = intervals.length;
int[] dp = new int[n];
int kept = 1;
for (int i = 0; i < n; i++) {
dp[i] = 1;
for (int j = 0; j < i; j++) {
if (intervals[j][1] <= intervals[i][0]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
kept = Math.max(kept, dp[i]);
}
return n - kept;
}
}
C++Tested in our runner
using namespace std;
class Solution {
public:
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end());
int n = intervals.size();
vector<int> dp(n, 1); // dp[i]: longest chain ending at i
int kept = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
if (intervals[j][1] <= intervals[i][0]) {
dp[i] = max(dp[i], dp[j] + 1);
}
}
kept = max(kept, dp[i]);
}
return n - kept;
}
};
JavaScriptTested in our runner
/**
* @param {number[][]} intervals
* @return {number}
*/
var eraseOverlapIntervals = function(intervals) {
intervals.sort((a, b) => a[0] - b[0]);
const n = intervals.length;
const dp = new Array(n).fill(1); // dp[i]: longest chain ending at i
let kept = 1;
for (let i = 0; i < n; i++) {
for (let j = 0; j < i; j++) {
if (intervals[j][1] <= intervals[i][0]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
kept = Math.max(kept, dp[i]);
}
return n - kept;
};
GoTested in our runner
import "sort"
func eraseOverlapIntervals(intervals [][]int) int {
sort.Slice(intervals, func(i, j int) bool {
return intervals[i][0] < intervals[j][0]
})
n := len(intervals)
dp := make([]int, n)
kept := 1
for i := 0; i < n; i++ {
dp[i] = 1
for j := 0; j < i; j++ {
if intervals[j][1] <= intervals[i][0] && dp[j]+1 > dp[i] {
dp[i] = dp[j] + 1
}
}
if dp[i] > kept {
kept = dp[i]
}
}
return n - kept
}
C#Tested in our runner
public class Solution {
public int eraseOverlapIntervals(int[][] intervals) {
Array.Sort(intervals, (a, b) => a[0].CompareTo(b[0]));
int n = intervals.Length;
int[] dp = new int[n];
int kept = 1;
for (int i = 0; i < n; i++) {
dp[i] = 1;
for (int j = 0; j < i; j++) {
if (intervals[j][1] <= intervals[i][0]) {
dp[i] = Math.Max(dp[i], dp[j] + 1);
}
}
kept = Math.Max(kept, dp[i]);
}
return n - kept;
}
}

Solution pattern
Interval Merging/Scheduling
Part of Greedy Patterns
Approach 3: Greedy: sort by end, keep the earliest finisherOptimalInterval Merging/Scheduling
What's slow: the DP checks every earlier interval to find the best predecessor. Most of that work is wasted, because the best choice is already known. The interval that ends first leaves the most room, so you never need to compare alternatives.
The insight that fixes it: sort by end point. Scan once and keep an interval whenever its start is at or after lastEnd. If it starts earlier, it overlaps a kept interval that ends no later than it does, so dropping it is never worse. Only a kept interval moves lastEnd.
Why it is correct. The invariant: after each step, kept is the largest count possible so far, and lastEnd is the smallest end achieving that count. Skipping an interval that starts too early never hurts, because a kept interval already ends no later than it does. So the greedy pick never loses a better answer.
Steps
- Sort the intervals by end point, smallest first.
- Set
lastEndto a value below every start, such as 0, andkeptto 0. - For each interval in order, compare its start with
lastEnd. - If
start >= lastEnd, keep it: add 1 tokeptand setlastEndto its end. - Otherwise skip it and leave
lastEndunchanged. - Return
n - kept.
Dry run
On [[1,3],[3,6],[6,10]], the ends are already 3, 6, 10, so the sorted order is unchanged. Start with lastEnd = 0, kept = 0.
| Step | Interval | start >= lastEnd? | Action | lastEnd | kept |
|---|---|---|---|---|---|
| 0 | (start) | 0 | 0 | ||
| 1 | [1,3] | 1 >= 0 yes | keep | 3 | 1 |
| 2 | [3,6] | 3 >= 3 yes | keep | 6 | 2 |
| 3 | [6,10] | 6 >= 6 yes | keep | 10 | 3 |
The answer is n - kept = 3 - 3 = 0. Each interval touches the previous end exactly, so the >= test is what keeps all three.
For contrast, take [[1,10],[2,4],[3,7],[8,9]]. The sorted order is [2,4],[3,7],[8,9],[1,10]. Keep [2,4], skip [3,7] since 3 < 4, keep [8,9] since 8 >= 4, skip [1,10] since 1 < 9. Kept is 2, so the answer is 4 - 2 = 2.
Complexity
| Time | O(n log n) |
|---|---|
| Space | O(1) |
Here n is the number of intervals. Sorting costs O(n log n) and the scan visits each interval once, which is O(n), so sorting dominates. Beyond the sort, the algorithm stores only lastEnd and kept, so extra space is O(1). The sort itself may use O(log n) to O(n) internal memory depending on the language.
PythonTested in our runner
from typing import List, Optional
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
intervals.sort(key=lambda iv: iv[1]) # earliest end first
kept = 0
last_end = 0 # every start is >= 1, so 0 accepts the first interval
for start, end in intervals:
if start >= last_end: # touching at an endpoint is allowed
kept += 1
last_end = end
return len(intervals) - kept
JavaTested in our runner
import java.util.*;
class Solution {
public int eraseOverlapIntervals(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> Integer.compare(a[1], b[1])); // earliest end first
int kept = 0;
int lastEnd = 0; // every start is >= 1
for (int[] iv : intervals) {
if (iv[0] >= lastEnd) {
kept++;
lastEnd = iv[1];
}
}
return intervals.length - kept;
}
}
C++Tested in our runner
using namespace std;
class Solution {
public:
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end(),
[](const vector<int>& a, const vector<int>& b) { return a[1] < b[1]; });
int kept = 0;
int lastEnd = 0; // every start is >= 1
for (const auto& iv : intervals) {
if (iv[0] >= lastEnd) {
kept++;
lastEnd = iv[1];
}
}
return (int)intervals.size() - kept;
}
};
JavaScriptTested in our runner
/**
* @param {number[][]} intervals
* @return {number}
*/
var eraseOverlapIntervals = function(intervals) {
intervals.sort((a, b) => a[1] - b[1]); // earliest end first
let kept = 0;
let lastEnd = 0; // every start is >= 1
for (const [start, end] of intervals) {
if (start >= lastEnd) {
kept++;
lastEnd = end;
}
}
return intervals.length - kept;
};
GoTested in our runner
import "sort"
func eraseOverlapIntervals(intervals [][]int) int {
sort.Slice(intervals, func(i, j int) bool {
return intervals[i][1] < intervals[j][1] // earliest end first
})
kept := 0
lastEnd := 0 // every start is >= 1
for _, iv := range intervals {
if iv[0] >= lastEnd {
kept++
lastEnd = iv[1]
}
}
return len(intervals) - kept
}
C#Tested in our runner
public class Solution {
public int eraseOverlapIntervals(int[][] intervals) {
Array.Sort(intervals, (a, b) => a[1].CompareTo(b[1])); // earliest end first
int kept = 0;
int lastEnd = 0; // every start is >= 1
foreach (var iv in intervals) {
if (iv[0] >= lastEnd) {
kept++;
lastEnd = iv[1];
}
}
return intervals.Length - kept;
}
}
Common mistakes
- Sorting by start with
sort(key=lambda iv: iv[0])and then greedily keeping. A long early interval such as[1,10]blocks many short ones. Sort by end instead. - Using
start > lastEnd(orstart <= lastEndas the overlap test). Intervals that touch at an endpoint are legal, so the keep condition must bestart >= lastEnd. - Updating
lastEnd = endfor a skipped interval. A skipped interval is removed, so it must not move the boundary. Only updatelastEndinside the keep branch. - Returning
keptinstead ofn - kept. The problem asks for the number removed, so subtract the kept count fromlen(intervals). - Initializing
lastEndto the first interval's end but still running the loop from index 0. The first interval then looks like it overlaps itself whenstart < end. Either start the loop at index 1 or use a sentinel below every start. - Comparing with
a[1] - b[1]in a sort for huge values in typed languages. Here values are at most 5 * 10^4, so it is safe. Still,Integer.compareis the habit that avoids overflow bugs elsewhere.
Edge cases
- A single interval
[[1,2]]: nothing can overlap, so the answer is 0. - Intervals that only touch,
[[1,3],[3,6],[6,10]]: the answer is 0, because shared endpoints are allowed. - Identical intervals
[[1,2],[1,2],[1,2]]: keep one and remove two, so the answer is 2. - One interval covering all others,
[[1,10],[2,4],[3,7],[8,9]]: remove[1,10]and one of the two middle ones, giving 2. - Already sorted and fully nested,
[[1,100],[2,50],[3,10]]: keep the innermost[3,10], answer 2. - Maximum size, 10^5 intervals: the O(n log n) sort and one scan finish quickly, while recursion or an O(n^2) DP would time out.
Follow-ups interviewers ask
- Why does sorting by start time with the same greedy fail?
- An interval with an early start can end very late. Keeping it blocks many short intervals that fit inside it, as in
[1,10]versus[2,4],[8,9]. The kept boundary is no longer as small as possible, so you may remove too many. Sorting by start works only if you also handle conflicts by dropping the interval with the larger end, which is the same greedy rule in disguise. - Can you do it without sorting by end, using sort by start and one scan?
- Yes. Sort by start. When the current interval overlaps the last kept one, remove one of them: keep the one with the smaller end, set
lastEnd = min(lastEnd, end), and count a removal. This gives the same answer in O(n log n), because the min rule is the same earliest-finish choice. - What if you must return which intervals to remove, not only the count?
- Record the index or the interval itself whenever the greedy skips it. Sort indices by end instead of sorting the array in place, so you can map back to the original order. The extra output is O(n) space and the time stays O(n log n).
Non-overlapping Intervals FAQ
What is the time complexity of Non-overlapping Intervals?
The greedy solution runs in O(n log n) time, where n is the number of intervals. Sorting by end costs O(n log n) and the single scan costs O(n). Extra space is O(1) beyond the sort.
Why use a greedy approach for Non-overlapping Intervals?
Removing the fewest intervals means keeping the most. The interval that ends earliest leaves the largest remaining timeline, so choosing it never hurts a later choice. That exchange argument makes the greedy pick optimal, which lets you skip the DP.
How do you check whether two intervals overlap?
Two intervals [a, b] and [c, d] overlap when a < d and c < b. In this problem, touching at an endpoint is not an overlap. After sorting by end, the check reduces to start < lastEnd.
Why sort by end time instead of start time?
Sorting by end lets you decide each interval with one comparison against the last kept end. An interval with a late end can only hurt later choices, so the earlier end is always preferred. Sorting by start gives a long early interval priority it does not deserve.
Can Non-overlapping Intervals be solved in O(1) extra space?
Almost. The scan itself uses O(1) extra space, but you must sort first. In-place sorting such as heap sort uses O(1) extra space, while the built-in sorts of Python, Java and others use O(log n) to O(n) internally. The sort also mutates the input unless you copy it.
What is the difference between Non-overlapping Intervals and Merge Intervals?
Merge Intervals combines overlapping intervals into larger ones and sorts by start. Non-overlapping Intervals chooses which intervals to delete so the rest do not overlap, and the best greedy sorts by end. Both begin with a sort and a single pass.
Asked at
See which companies ask this — Pro
Related problems
- Merge Intervals · same technique: Interval Merging/Scheduling
- Insert Interval · same technique: Interval Merging/Scheduling
- Divide Intervals Into Minimum Number of Groups · same technique: Interval Merging/Scheduling
- Meeting Rooms · same technique: Interval Merging/Scheduling
- Candy · next harder, same pattern
- Jump Game · same pattern: Greedy Patterns
- Gas Station · same pattern: Greedy Patterns
- Task Scheduler · same pattern: Greedy Patterns
- Jump Game II · same pattern: Greedy Patterns
- Partition Labels · same pattern: Greedy Patterns