#1288

Remove Covered Intervals

Medium
ArraySortingSortingGreedy Algorithm
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

The optimal approach involves sorting the intervals first and then iterating through them to count non-covered intervals. By sorting, we can efficiently determine coverage based on the start and end points.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the intervals by starting point, and by ending point in descending order if starting points are the same.
  2. 2Step 2: Initialize a variable to track the end of the last added interval.
  3. 3Step 3: Iterate through the sorted intervals, and for each interval, check if its end is greater than the last added end. If so, increment the count and update the last added end.
solution.py9 lines
1def removeCoveredIntervals(intervals):
2    intervals.sort(key=lambda x: (x[0], -x[1]))
3    count = 0
4    last_end = 0
5    for interval in intervals:
6        if interval[1] > last_end:
7            count += 1
8            last_end = interval[1]
9    return count

Complexity note: The complexity is dominated by the sorting step, which is O(n log n). The subsequent iteration is O(n).

  • 1Sorting helps in efficiently determining coverage.
  • 2Using a single pass after sorting reduces complexity.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.