Remove Covered Intervals - Problem

Given an array intervals where intervals[i] = [li, ri] represent the interval [li, ri), remove all intervals that are covered by another interval in the list.

An interval [a, b) is covered by interval [c, d) if and only if c ≤ a and b ≤ d.

Return the number of remaining intervals after removing all covered intervals.

Input & Output

Example 1 — Basic Coverage
$ Input: intervals = [[1,4],[3,6],[2,8]]
Output: 2
💡 Note: Interval [3,6] is covered by [2,8] because 2 ≤ 3 and 6 ≤ 8. So [1,4] and [2,8] remain.
Example 2 — No Coverage
$ Input: intervals = [[1,4],[2,3]]
Output: 1
💡 Note: Interval [2,3] is covered by [1,4] because 1 ≤ 2 and 3 ≤ 4. Only [1,4] remains.
Example 3 — Multiple Covered
$ Input: intervals = [[1,2],[1,4],[3,4]]
Output: 1
💡 Note: [1,4] covers both [1,2] and [3,4]. Only [1,4] remains.

Constraints

  • 1 ≤ intervals.length ≤ 1000
  • intervals[i].length == 2
  • 0 ≤ li < ri ≤ 105

Visualization

Tap to expand
Remove Covered Intervals INPUT intervals = [[1,4],[3,6],[2,8]] Number Line (0-9) 0 1 2 3 4 5 6 7 8 [1,4] [3,6] [2,8] 3 intervals total Check which are covered by others ALGORITHM STEPS 1 Sort Intervals By start ASC, end DESC [[1,4],[2,8],[3,6]] 2 Track Max End maxEnd = 0 initially 3 Iterate and Check If end <= maxEnd: covered [1,4]: 4>0 --> count=1, max=4 [2,8]: 8>4 --> count=2, max=8 [3,6]: 6<=8 --> COVERED! (skip, don't count) 4 Return Count Non-covered intervals: 2 FINAL RESULT Remaining Intervals: 0 1 2 3 4 5 6 7 8 [1,4] [2,8] [3,6] covered Output: 2 remaining intervals OK - [3,6] removed (covered by [2,8]) Key Insight: Sorting by start ASC and end DESC ensures that for intervals with the same start, the longer one comes first. Then we only need to track the maximum end point seen. If current interval's end <= maxEnd, it's covered. Time: O(n log n), Space: O(1) TutorialsPoint - Remove Covered Intervals | Optimal Solution
Asked in
Google 15 Amazon 12 Microsoft 8
18.0K 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