Problem Description
Given a list of intervals, remove all intervals that are covered by another interval in the list. An interval [a, b) is covered by another interval [c, d) if and only if c <= a and b <= d. The goal is to return the number of remaining intervals after removal.
Key Insights
- Sort intervals by their start points in ascending order and by end points in descending order when starts are equal.
- By sorting this way, if two intervals have the same start, the longer interval comes first, making it easier to detect coverage.
- Keep track of the maximum end encountered so far.
- When iterating, if the current interval's end is less than or equal to the tracked maximum end, it is covered by a previous interval.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting, with an additional O(n) for a single pass through the intervals. Space Complexity: O(1) extra space if the sort is in-place.
Solution
The solution involves a greedy approach:
- Sort the intervals by start coordinate in ascending order; if two intervals share the same start, sort them by their end coordinate in descending order.
- Initialize a counter for the number of non-covered intervals and a variable to record the farthest end encountered.
- Iterate through the sorted list. For each interval, if its end is greater than the maximum end seen so far, it is not covered and should be counted; update the maximum end.
- Return the count.
This technique ensures each interval is processed only once after sorting, which yields an efficient and optimal solution.