Remove Covered Intervals - Problem
Given an array of intervals where intervals[i] = [li, ri] represents the interval [li, ri) (left-inclusive, right-exclusive), your task is to eliminate all intervals that are completely covered by another interval in the list.
An interval [a, b) is considered covered by interval [c, d) if and only if c ≤ a and b ≤ d. In other words, one interval completely contains another.
Goal: Return the number of intervals that remain after removing all covered intervals.
Example: If we have intervals [[1,4), [3,6), [2,8)], then [1,4) is covered by [2,8) since 2 ≤ 1 is false, but [3,6) is covered by [2,8) since 2 ≤ 3 and 6 ≤ 8.
Input & Output
example_1.py — Basic Case
$
Input:
intervals = [[1,4],[3,6],[2,8]]
›
Output:
2
💡 Note:
Interval [3,6] is covered by [2,8], so we remove it. Intervals [1,4] and [2,8] remain.
example_2.py — No Covered Intervals
$
Input:
intervals = [[1,2],[1,4],[3,4]]
›
Output:
2
💡 Note:
Interval [1,2] is covered by [1,4]. The remaining intervals are [1,4] and [3,4].
example_3.py — Single Interval
$
Input:
intervals = [[1,3]]
›
Output:
1
💡 Note:
Only one interval exists, so it cannot be covered by another interval.
Constraints
- 1 ≤ intervals.length ≤ 1000
- intervals[i].length == 2
- 0 ≤ li ≤ ri ≤ 105
- All intervals are unique (no duplicate intervals)
Visualization
Tap to expand
Understanding the Visualization
1
Organize Books
Sort books by their starting position on the shelf
2
Track Coverage
Keep track of the furthest right position covered by books we've kept
3
Remove Covered
Any book that ends before our furthest right position is covered by a previous book
4
Count Remaining
Count how many books remain after removing covered ones
Key Takeaway
🎯 Key Insight: By sorting intervals and tracking the maximum end point, we can identify covered intervals in O(n log n) time instead of O(n²).
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code