Non-overlapping Intervals
Non-overlapping Intervals
IntervalsArraysGreedy
Problem Statement
Given an array of intervals intervals
where intervals[i] = [start_i, end_i]
, return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Example
Example 1:
Input: intervals = [[1,2],[2,3],[3,4],[1,3]]
Initial Intervals:
[1, 2]
[2, 3]
[3, 4]
[1, 3]
Minimum Removals:
1
Output: 1
Explanation: [1,3] can be removed and the rest of the intervals are non-overlapping.
Solution
This is a classic greedy problem. To minimize removals, we should keep intervals that finish as early as possible. This leaves the maximum amount of room for subsequent intervals.
Algorithm Steps
- Sort the intervals based on their end times.
- Initialize a counter for removals to 0 and track the end of the last kept interval.
- Iterate through the sorted intervals. If the current interval's start is before the end of the last kept interval, it overlaps and must be "removed" (increment counter).
- Otherwise, keep the current interval and update the "last end" tracker.
Intervals
[1, 2]
[2, 3]
[3, 4]
[1, 3]
Removals: 0
Start with the unsorted intervals.
Non-overlapping Intervals Solution