435. Non-overlapping Intervals
LeetCode 435. Non-overlapping Intervals
Description
Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Example 1:
Example 2:
Example 3:
Constraints:
1 <= intervals.length <= 2 * 10^4
intervals[i].length == 2
-2 * 10^4 <= starti < endi <= 2 * 10^4
Note:
You may assume the interval's end point is always bigger than its start point.
Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other.
Tags
Greedy, Sort
Solution
Finding the minimum number of intervals to be removed is equivalent to keeping as many non-overlapping intervals as possible. Thus, our greedy strategy is to preferably retain the non-intersecting invervals with smaller right interval.
To implement this, we firstly sort the given invervals by the right interval of each in ascending order. Then, compare each interval with its previous retained interval. If there is an overlap between the two intervals, the current one should be discarded, and the result will be increased by 1. Otherwise, we update the previous interval with the current one.
Complexity
Time complexity: , depending on the sort algorithm;
Space complexity: , depending on the sort algorithm.
Code
Reference
Last updated
Was this helpful?