435. Non-overlapping Intervals
Asked at 17Amazon44Bloomberg39Google34Meta33Microsoft30Grammarly90Verkada85Zoho52IBM50PayPal42Visa39Roblox37tcs36TikTok35Oracle27Uber22Goldman Sachs21
Problem
Return the minimum number of intervals to remove so that the rest don't overlap. Intervals that only touch (like [1,2] and [2,3]) don't overlap.
Example: [[1,2],[2,3],[3,4],[1,3]] → 1; [[1,2],[1,2],[1,2]] → 2
Constraints: up to 10⁵ intervals.
Min removals = n − (max non-overlapping set). Greedy activity selection: sort by end, keep an interval if it starts at/after the last kept end.
Complexity: O(n log n).
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
keep, end = 0, float("-inf")
for s, e in sorted(intervals, key=lambda x: x[1]):
if s >= end:
keep += 1
end = e
return len(intervals) - keep
assert Solution().eraseOverlapIntervals([[1, 2], [2, 3], [3, 4], [1, 3]]) == 1
assert Solution().eraseOverlapIntervals([[1, 2], [1, 2], [1, 2]]) == 2
assert Solution().eraseOverlapIntervals([[1, 2], [2, 3]]) == 0
class Solution {
public int eraseOverlapIntervals(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> Integer.compare(a[1], b[1]));
int keep = 0;
long end = Long.MIN_VALUE;
for (int[] iv : intervals) if (iv[0] >= end) { keep++; end = iv[1]; }
return intervals.length - keep;
}
}
func eraseOverlapIntervals(intervals [][]int) int {
sort.Slice(intervals, func(i, j int) bool { return intervals[i][1] < intervals[j][1] })
keep, end := 0, math.MinInt
for _, iv := range intervals { // keep the interval that ends first, as often as possible
if iv[0] >= end {
keep++
end = iv[1]
}
}
return len(intervals) - keep
}