sagelearnai

Remove Covered Intervals

Difficulty: Medium · Pattern: Intervals · LeetCode #1288

Remove every interval that is covered by another one ([a,b] is covered by [c,d] if c ≤ a and b ≤ d). Return the number of intervals left.

Examples

text
[[1,4],[3,6],[2,8]]  →  2    ([3,6] is covered by [2,8])
[[1,4],[2,3]]        →  1

Hints

  1. Sort by start ascending. For equal starts, put the longer interval first, so it covers the shorter ones.
  2. Then an interval is covered exactly when its end ≤ the largest end seen so far.

Approach

Sort by (start, −end), then sweep while tracking maxEnd. If end > maxEnd, the interval is not covered: count it and update maxEnd. Otherwise it's covered by some earlier interval (one with a smaller or equal start and a larger or equal end).

The tie-break matters. With [1,4] and [1,6], sorting [1,4] first would count both, but [1,4] is covered.

Complexity

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

Python solution
def removeCoveredIntervals(intervals):
    count, max_end = 0, -1
    for s, e in sorted(intervals, key=lambda x: (x[0], -x[1])):
        if e > max_end:
            count += 1
            max_end = e
    return count
JavaScript solution
function removeCoveredIntervals(intervals) {
  const a = [...intervals].sort((x, y) => x[0] - y[0] || y[1] - x[1]);
  let count = 0, maxEnd = -1;
  for (const [, e] of a) if (e > maxEnd) { count++; maxEnd = e; }
  return count;
}