Problem Description
Given an array of intervals where each interval is represented as [start, end], the goal is to remove the minimum number of intervals so that the remaining intervals do not overlap. Note that intervals that only touch (i.e. end of one equals start of the other) are considered non-overlapping.
Key Insights
- Sorting is the key: By sorting intervals by their end times, we can greedily choose the optimal set of non-overlapping intervals.
- Greedy approach: Always select the interval that ends the earliest, as it leaves maximum room for subsequent intervals.
- Counting removals: The answer is the total number of intervals minus the count of intervals selected by this greedy approach.
- Edge observation: Intervals that touch at the boundary are not overlapping, so the check uses “>=” instead of “>”.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting the intervals. Space Complexity: O(n) if considering the storage for the sorted list (or O(1) if sorting in-place).
Solution
The solution involves first sorting the intervals by their end times. Initialize a variable to track the end of the last chosen interval. Iterate over the sorted intervals: if the current interval’s start is greater than or equal to the last chosen interval’s end, update the last end and include this interval in the non-overlapping set. Otherwise, count the interval as one that must be removed. The final answer is the removal count, which is computed as the total number of intervals minus the count of non-overlapping intervals selected.