Remove Covered Intervals Problem
Description
LeetCode Problem 1288.
Given an array intervals where intervals[i] = [l_i, r_i] represent the interval [l_i, r_i), remove all intervals that are covered by another interval in the list.
The interval [a, b) is covered by the interval [c, d) if and only if c <= a and b <= d.
Return the number of remaining intervals.
Example 1:
Input: intervals = [[1,4],[3,6],[2,8]]
Output: 2
Explanation: Interval [3,6] is covered by [2,8], therefore it is removed.
Example 2:
Input: intervals = [[1,4],[2,3]]
Output: 1
Constraints:
1 <= intervals.length <= 1000intervals[i].length == 20 <= l_i < r_i <= 10^5- All the given intervals are unique.
Solution
Approach: Sort, Then Track the Furthest Right End
Sort the intervals by left end ascending, and for equal left ends by right end descending. After sorting, any interval that can cover the current one comes before it: a cover needs a left end that is no larger, and among intervals with the same left end the longer ones are placed first.
Walk through the sorted list and keep reach, the largest right end seen so far. Every earlier interval starts at or before the current one, so the current interval is covered exactly when some earlier interval also ends at or after it, i.e. when right <= reach. Otherwise it survives: count it and update reach.
The descending tie-break is the subtle part. With [1, 2] and [1, 4], putting [1, 4] first sets reach = 4 and [1, 2] is correctly found covered. In ascending order [1, 2] would be counted before its cover appears.
Complexity: O(n log n) time for the sort and O(1) extra space besides it.
class Solution:
def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:
# Left ends ascending; for equal left ends, the longest interval first.
intervals.sort(key=lambda e: (e[0], -e[1]))
remaining = 0
reach = -1 # largest right end seen so far
for _, right in intervals:
if right > reach: # not covered by any earlier interval
remaining += 1
reach = right
return remaining