435. Non-overlapping Intervals
Intuition
To minimize the number of intervals that need to be removed to make the remaining intervals non-overlapping, we should:
- Sort the intervals by their end time
- Keep track of the current end time
- Remove intervals that overlap with the current end time
Approach
- Sort all intervals based on their end time in ascending order
- Initialize variables:
end
: tracks the end time of the last valid interval (initialized to -50001)ret
: counts the number of intervals that need to be removed
- Iterate through the sorted intervals:
- If current interval's start time is greater than or equal to previous end time:
- Update end time to current interval's end time
- Otherwise:
- Increment the removal counter (ret)
- If current interval's start time is greater than or equal to previous end time:
- Return the total number of intervals that need to be removed
Complexity
- Time complexity: O(nlogn)
- Space complexity: O(1)
Keywords
- Array
- Sorting
- Greedy
- Interval Scheduling