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
Library Shelf - Remove Covered IntervalsBook A[1,4)Book B[2,8)Book C[3,6)COVEREDRemove!Result: 2 books remain (A and B)
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²).
Asked in
Facebook 15 Google 12 Amazon 8 Microsoft 6
24.7K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen