Algo-Sim › Intervals
Non-overlapping Intervals
Medium · Intervals · step through it in Java, Python and C++ on your own input
Find the minimum number of intervals to remove so that the rest do not overlap. Touching ends are fine.
Problem
Given a list of intervals, return the fewest intervals you must delete so that none of the remaining ones overlap. Intervals that only touch at an endpoint, such as [1, 2] and [2, 3], do not overlap.
Constraints
- 1 ≤ intervals.length ≤ 10⁵
- -5 · 10⁴ ≤ start < end ≤ 5 · 10⁴
- n up to 10⁵ calls for an O(n log n) greedy
Edge cases to test
- No overlaps:
0 - All intervals identical
- Touching ends do not overlap
Follow-up questions
- Why sort by end, not start?
- Keeping the interval that ends first leaves the most room for the rest: the activity-selection exchange argument. O(n log n).
- How is this related to Minimum Arrows?
- It is the same greedy: the number of non-overlapping intervals you keep equals the arrows needed (LC 452), with the overlap rule for touching ends flipped.
Solution
Java
public int eraseOverlapIntervals(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> Integer.compare(a[1], b[1]));
int removed = 0, prevEnd = Integer.MIN_VALUE;
for (int[] cur : intervals) {
if (cur[0] >= prevEnd) {
prevEnd = cur[1];
} else {
removed++;
}
}
return removed;
}Python
def erase_overlap_intervals(intervals):
intervals.sort(key=lambda iv: iv[1])
removed, prev_end = 0, float("-inf")
for cur in intervals:
if cur[0] >= prev_end:
prev_end = cur[1]
else:
removed += 1
return removedC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int eraseOverlapIntervals(vector<vector<int>> &intervals) {
sort(intervals.begin(), intervals.end(), [](const auto &a, const auto &b) { return a[1] < b[1]; });
int removed = 0, prevEnd = INT_MIN;
for (vector<int> &cur : intervals) {
if (cur[0] >= prevEnd) {
prevEnd = cur[1];
} else {
removed++;
}
}
return removed;
}
};
More Intervals problems
- Merge Intervals (Medium)
- Insert Interval (Medium)
- Meeting Rooms (Easy)
- Meeting Rooms II (Medium)
- Car Pooling (Difference Array) (Medium)
- My Calendar I (Medium)
- Minimum Interval to Include Each Query (Hard)