Non-overlapping Intervals
Medium greedy · intervals
Description
Constraints
1 <= intervals <= 100000
Examples
Input: intervals = [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Hints (1)
- Sort by end time and keep the interval that finishes earliest.
Solutions
Sort by end, keep earliest finish. (requires "sort") · Time O(n log n) · Space O(1)
func eraseOverlapIntervals(intervals [][]int) int {
sort.Slice(intervals, func(i, j int) bool { return intervals[i][1] < intervals[j][1] })
removed, end := 0, -1<<62
for _, iv := range intervals {
if iv[0] < end {
removed++
} else {
end = iv[1]
}
}
return removed
}
Sort by end, keep earliest finish. · Time O(n log n) · Space O(1)
function eraseOverlapIntervals(intervals) {
intervals = [...intervals].sort((a, b) => a[1] - b[1]);
let removed = 0, end = -Infinity;
for (const iv of intervals) {
if (iv[0] < end) removed++;
else end = iv[1];
}
return removed;
}
Sort by end, keep earliest finish. · Time O(n log n) · Space O(1)
function eraseOverlapIntervals($intervals) {
usort($intervals, fn ($a, $b) => $a[1] <=> $b[1]);
$removed = 0; $end = PHP_INT_MIN;
foreach ($intervals as $iv) {
if ($iv[0] < $end) { $removed++; } else { $end = $iv[1]; }
}
return $removed;
}
Sort by end, keep earliest finish. · Time O(n log n) · Space O(1)
def eraseOverlapIntervals(intervals):
removed = 0
end = float("-inf")
for start, stop in sorted(intervals, key=lambda x: x[1]):
if start < end:
removed += 1
else:
end = stop
return removed
Sort by end, keep earliest finish. · Time O(n log n) · Space O(1)
function eraseOverlapIntervals(intervals: number[][]): number {
const sorted = [...intervals].sort((a, b) => a[1] - b[1]);
let removed = 0, end = -Infinity;
for (const iv of sorted) {
if (iv[0] < end) removed++;
else end = iv[1];
}
return removed;
}
Create a free account to submit solutions, track progress and save problems.
Create account