Remove Covered Intervals

medium intervals sorting

Problem

Given a list of intervals, remove all intervals that are covered by another in the list. An interval [a, b) is covered by [c, d) if c ≤ a and b ≤ d. Return the number of remaining intervals.

Inputintervals = [[1,4],[3,6],[2,8]]
Output2
[3,6] is covered by [2,8]. The survivors are [1,4] and [2,8].

def remove_covered_intervals(intervals):
    intervals.sort(key=lambda x: (x[0], -x[1]))
    count = 0
    max_end = 0
    for a, b in intervals:
        if b > max_end:
            count += 1
            max_end = b
    return count
function removeCoveredIntervals(intervals) {
  intervals.sort((a, b) => a[0] - b[0] || b[1] - a[1]);
  let count = 0, maxEnd = 0;
  for (const [a, b] of intervals) {
    if (b > maxEnd) { count++; maxEnd = b; }
  }
  return count;
}
class Solution {
    public int removeCoveredIntervals(int[][] intervals) {
        Arrays.sort(intervals, (x, y) -> x[0] != y[0] ? x[0] - y[0] : y[1] - x[1]);
        int count = 0, maxEnd = 0;
        for (int[] iv : intervals) {
            if (iv[1] > maxEnd) { count++; maxEnd = iv[1]; }
        }
        return count;
    }
}
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 count = 0, maxEnd = 0;
    for (auto& iv : intervals) {
        if (iv[1] > maxEnd) { count++; maxEnd = iv[1]; }
    }
    return count;
}
Time: O(n log n) Space: O(1) extra