|
| 1 | +# Non-Overlapping Intervals |
| 2 | + |
| 3 | +Write a function to return the minimum number of intervals that must be removed from a given array intervals, where |
| 4 | +intervals[i] consists of a starting point starti and an ending point endi, to ensure that the remaining intervals do not |
| 5 | +overlap. |
| 6 | + |
| 7 | +Example: |
| 8 | + |
| 9 | +```text |
| 10 | +intervals = [[1,3],[5,8],[4,10],[11,13]] |
| 11 | +1 |
| 12 | +
|
| 13 | +Explanation: Removing the interval [4,10] leaves all other intervals non-overlapping. |
| 14 | +``` |
| 15 | + |
| 16 | +## Solution |
| 17 | + |
| 18 | +This question reduces to finding the maximum number of non-overlapping intervals. Once we know that value, then we can |
| 19 | +subtract it from the total number of intervals to get the minimum number of intervals that need to be removed. |
| 20 | + |
| 21 | + |
| 22 | + |
| 23 | +To find the maximum number of non-overlapping intervals, we can sort the intervals by their end time. We then use a |
| 24 | +greedy approach: we iterate over each sorted interval, and repeatedly try to add that interval to the set of |
| 25 | +non-overlapping intervals. Sorting by the end time allows us to choose the intervals that end the earliest first, which |
| 26 | +frees up more time for intervals to be included later. |
| 27 | +We start by keeping track of a variable end which represents the end time of the latest interval in our set of |
| 28 | +non-overlapping intervals, as well as a variable count which represents the number of non-overlapping intervals we have |
| 29 | +found so far. |
| 30 | + |
| 31 | + |
| 32 | + |
| 33 | + |
| 34 | +We then iterate over each interval starting from the second interval in the list (the first interval is always |
| 35 | +non-overlapping). For each interval, we compare the start time of the interval to end. If it is less than end, then we |
| 36 | +cannot add the interval to our set of non-overlapping intervals, so we move onto the next interval without updating end or |
| 37 | +count. |
| 38 | + |
| 39 | + |
| 40 | + |
| 41 | + |
| 42 | +If it is greater than or equal to end, then we can add the interval to our set of non-overlapping intervals by updating |
| 43 | +count. We then update the value of end to be the end time of the current interval. |
| 44 | + |
| 45 | + |
| 46 | + |
| 47 | + |
| 48 | + |
| 49 | + |
| 50 | + |
| 51 | + |
| 52 | +### Complexity Analysis |
| 53 | + |
| 54 | +#### Time Complexity |
| 55 | + |
| 56 | +O(n * logn) where n is the number of intervals. The time complexity is dominated by the sorting step. |
| 57 | + |
| 58 | +#### Space Complexity |
| 59 | + |
| 60 | +We only initialize two extra variables regardless of the input size. |
| 61 | + |
0 commit comments