Non-overlapping Intervals
Pattern: Intervals greedy
Removing the fewest intervals is keeping the most non-overlapping ones. Sort by end and keep every interval that starts at or after the last kept end; the answer is n minus the number kept.
The problem
Return the fewest intervals to remove so the rest do not overlap. Intervals that only touch, like [1, 2] and [2, 3],
do not overlap. [[1, 2], [2, 3], [3, 4], [1, 3]] gives 1.
Think first
- What is the opposite question?
- Which interval is safest to keep first?
- Do touching intervals overlap here?
Hints
Brute force, and why it fails
Try every subset to keep: O(2ⁿ × n).
The key insight
It is activity selection in disguise: the earliest-ending interval is always safe to keep.
Dry run
| lastEnd | none |
|---|
[[1, 2], [2, 3], [3, 4], [1, 3]] sorted by end: [1, 2], [2, 3], [1, 3], [3, 4].
Step 1 of 4
The plan
sort by end; kept = 0; lastEnd = -infinity
for (s, e): if s >= lastEnd: kept += 1; lastEnd = e
return n - kept
Complexity
- Time
O(n log n)- Space
O(n)
Sorting dominates.
Edge cases
- All equal intervals: keep one.
- Already non-overlapping: 0.
- Negative coordinates.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int eraseOverlapIntervals(int[][] intervals) {
int[][] byEnd = intervals.clone();
Arrays.sort(byEnd, (a, b) -> Integer.compare(a[1], b[1])); // earliest end first
int kept = 0;
long lastEnd = Long.MIN_VALUE;
for (int[] iv : byEnd) {
if (iv[0] >= lastEnd) { // touching at a point is not an overlap
kept++;
lastEnd = iv[1];
}
}
return intervals.length - kept; // remove everything not kept
}
}C++
class Solution {
public:
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
vector<vector<int>> byEnd(intervals);
sort(byEnd.begin(), byEnd.end(), [](const vector<int>& a, const vector<int>& b) { return a[1] < b[1]; });
int kept = 0;
long long lastEnd = LLONG_MIN;
for (const vector<int>& iv : byEnd) { // earliest end first
if (iv[0] >= lastEnd) { // touching at a point is not an overlap
kept++;
lastEnd = iv[1];
}
}
return static_cast<int>(intervals.size()) - kept; // remove everything not kept
}
};Python
class Solution:
def eraseOverlapIntervals(self, intervals: list[list[int]]) -> int:
kept, last_end = 0, float("-inf")
for s, e in sorted(intervals, key=lambda iv: iv[1]): # earliest end first
if s >= last_end: # touching at a point is not an overlap
kept += 1
last_end = e
return len(intervals) - kept # remove everything not keptCommon mistakes
- Sorting by start and keeping the first of each overlap.
- Treating touching intervals as overlapping.