1288. Remove Covered Intervals
Problem
Interval [a, b) is covered by [c, d) if c ≤ a and b ≤ d. Remove every interval covered by another one and return how many remain.
Example: [[1,4],[3,6],[2,8]] → 2 ([3,6] is covered by [2,8])
Constraints: up to 1000 intervals, all distinct.
Sort by start ascending and end descending (so a longer interval with the same start comes first). Sweep tracking the max end; an interval whose end ≤ max end is covered.
Complexity: O(n log n).
class Solution:
def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:
keep, max_end = 0, -1
for s, e in sorted(intervals, key=lambda x: (x[0], -x[1])):
if e > max_end:
keep += 1
max_end = e
return keep
assert Solution().removeCoveredIntervals([[1, 4], [3, 6], [2, 8]]) == 2
assert Solution().removeCoveredIntervals([[1, 4], [2, 3]]) == 1
class Solution {
public int removeCoveredIntervals(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> a[0] != b[0] ? a[0] - b[0] : b[1] - a[1]);
int keep = 0, maxEnd = -1;
for (int[] iv : intervals) if (iv[1] > maxEnd) { keep++; maxEnd = iv[1]; }
return keep;
}
}
func removeCoveredIntervals(intervals [][]int) int {
sort.Slice(intervals, func(i, j int) bool { // start up; for equal starts the longest first
a, b := intervals[i], intervals[j]
return a[0] < b[0] || a[0] == b[0] && a[1] > b[1]
})
keep, maxEnd := 0, -1
for _, iv := range intervals { // covered exactly when an earlier interval reaches as far
if iv[1] > maxEnd {
keep++
maxEnd = iv[1]
}
}
return keep
}