Solution: Remove Covered Intervals
Let’s solve the Remove Covered Intervals problem using the Merge Intervals pattern.
We'll cover the following
Statement
Given an array of intervals
, where each interval is represented as intervals[i]
Note: An interval
is considered covered by another interval if and only if and .
Constraints:
intervals.length
intervals[i].length
All the given intervals are unique.
Solution
The first step is to simplify the process by sorting the intervals. Sorting by the start point in ascending order is straightforward and simplifies the iteration process. However, an important edge case arises when two intervals share the same start point. In such scenarios, sorting solely by the start point would fail to correctly identify covered intervals. To handle this, we sort intervals with the same start point by their endpoint in descending order, ensuring that longer intervals come first. This sorting strategy guarantees that if one interval covers another, it will be positioned earlier in the sorted list. Once the intervals are sorted, we iterate through them while keeping track of the maximum endpoint seen so far. If the current interval’s end point exceeds this maximum, it is not covered, so we increment the count and update the maximum end. The interval is covered and skipped if the endpoint is less than or equal to the maximum. After completing the iteration, the final count reflects the remaining non-covered intervals.
Now, let’s look at the solution steps below:
If the start points are the same, sort the
intervals
by the start point in ascending order, otherwise, sort by the endpoint in descending order to prioritize longer intervals.Initialize the
count
with zero to track the remaining (non-covered) intervals.Initialize
prevEnd
with zero to track the maximum end value we’ve seen..Start iterating through
intervals
for each interval[start, end]
in the sorted list:If
end
>prevEnd
, any previous interval does not cover the interval.Increment
count
by. Update
prevEnd
toend
.
Else:
A previous interval covers the interval, so we skip it.
After iterating through all the intervals, the return
count
is the final value, representing the remaining intervals.
Let’s look at the following illustration to get a better understanding of the solution:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.