greedy
sort
line sweep
intervals
]
Leetcode 1288. Remove Covered Intervals
https://leetcode.com/problems/remove-covered-intervals
Let us sort our intervals by their starts and traverse them one by one (if we have the same ends, we first choose intervals with smaller ends, so they will be traversed first) Also let us keep right
variable, which will be the biggest right end of interval so far. So, what does it mean that one interval is covered by some other? It means that end <= right
: we have some previous interval with end more than current end and start which is less than current interval.
Complexity: for time complexity we sort intervals in O(n log n)
and then traverse them in O(n)
. Space complexity is O(n)
if we are not allowed to change intervals
and O(log n)
we are allowed to modify intervals
.
class Solution:
def removeCoveredIntervals(self, intervals):
intervals.sort(key = lambda x: (x[0], -x[1]))
right, rem, n = -1, 0, len(intervals)
for _, end in intervals:
if end <= right:
rem += 1
else:
right = end
return n - rem
If you like the solution, you can upvote it on leetcode discussion section: Problem 1288