Statement▼
Given an array of intervals where intervals[i]
contains the
Note: Two intervals
(a,b] and(c,d] are considered overlapping if there exists a valuex such thata<x≤b andc<x≤d . In other words, if there is any point within both intervals (excluding their starting points) where both intervals have values, they are considered overlapping. For example, the intervals(7,11] and(10,12] are overlapping, whereas the intervals(2,4] and(4,5] are non-overlapping.
Constraints:
1≤ intervals.length
≤103 intervals[i].length
==2 −5×104≤starti<endi≤5×104
Solution
Here are the steps of the algorithm:
Sort the
intervals
array in an ascending order based on the end time of each interval.Declare two variables that will assist us in the algorithm:
end
: This stores the end time of the last included interval.remove
: This stores the number of intervals to be removed. It is initialized to0 .
Traverse the sorted
intervals
array to determine which interval needs to be excluded. For each interval, the following conditions are checked:If the start time of the current interval is greater than or equal to
end
, this interval does not overlap with the previously included interval and can be included. Therefore, we updateend
to the end time of the current interval, which is the next earliest possible end time.Otherwise, the current interval overlaps with the previously included intervals. Therefore, it must be removed, so we increment
remove
.
After the sorted
intervals
array has been traversed completely, there are no more intervals left to evaluate, so we returnremove
, which now contains the minimum number of intervals to be removed.
The slides below illustrate how the algorithm runs: