![]() |
VOOZH | about |
Given a 2D array intervals[][], where intervals[i] =[starti, endi]. Find the minimum number of intervals need to be removed to make the rest of the intervals non-overlapping.
Note: Two intervals are considered non-overlapping if the end time of one interval is less than or equal to the start time of the next interval.
Examples:
Input: intervals[][] = [[1, 2], [2, 3], [3, 4], [1, 3]]
Output: 1
Explanation: Removal of [1, 3] makes the ranges non-overlapping.Input: intervals[][] = [[1, 3], [1, 3], [1, 3]]
Output: 2
Explanation: Removal of two occurrences of [1, 3] makes the remaining ranges non-overlapping.Input: intervals[][] = [[1, 2], [5, 10], [18, 35], [40, 45]]
Output: 0
Explanation: All ranges are already non-overlapping.
Table of Content
The idea is to use a greedy approach to select the interval to be removed, such that removal count is minimized. First we sort the intervals by their starting values. Then traverse through the interval array and check if any interval has a starting point smaller than the ending point of the previous interval (ie. there is an overlap). Incase overlapping occurs remove the interval with greater ending point.
1
To understand this approach, think of it as trying to keep intervals short so we have more space for other intervals, without overlap. By sorting intervals by their end times, we can easily check if the next interval overlaps with the previous one. If there’s an overlap, we remove the interval with the later end time, so it doesn’t block the next intervals from fitting in. This way, we end up with the minimum number of removals needed to make all intervals non-overlapping.
1