Remove Covered Intervals

Count intervals not covered by another after sorting by start ascending, end descending.

Medium
Time O(n log n) Space O(1)
LeetCode
3 min read
intervals sorting

Problem#

Return the number of intervals that remain after removing every interval covered by some other interval.

Examples#

  • [[1,4],[3,6],[2,8]]2 (drop [3,6])

Constraints#

  • 1 <= intervals.length <= 1000.

Approach#

Sort by start ascending, with end descending as the tiebreaker. Then a single pass: an interval is not covered iff its end exceeds the max end seen so far. The tiebreaker ensures that when two intervals share the start, the longer comes first — making the shorter automatically detect as covered.

Solution#

Remove Covered Intervals
class Solution {
public:
int removeCoveredIntervals(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end(), [](auto& a, auto& b){
return a[0] != b[0] ? a[0] < b[0] : a[1] > b[1];
});
int kept = 0, maxEnd = 0;
for (auto& it : intervals) {
if (it[1] > maxEnd) { ++kept; maxEnd = it[1]; }
}
return kept;
}
};

Editorial#

The combined sort order is the trick. With start ascending, all later intervals have start ≥ current. With end descending on ties, equal starts put the longest interval first; equal-start intervals after it are necessarily covered. So checking “does my end extend the running max?” suffices.

Complexity#

  • Time: O(n log n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.