Leetcode Problem 435: Non-overlapping Intervals
Given an array of 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:
intervals = [[1,2],[2,3],[3,4],[1,3]]
1
Explanation: The interval [1,3] can be removed and the rest of the intervals are non-overlapping.
intervals = [[1,2],[1,2],[1,2]]
2
Explanation: You need to remove two [1,2] to make the rest of the intervals non-overlapping.
intervals = [[1,2],[2,3]]
0
The optimal approach to solve this problem uses a Greedy Algorithm. Here’s the detailed plan:
Below is the Python code implementing the above strategy:
def eraseOverlapIntervals(intervals):
# If there are no intervals, we don't need to remove anything
if not intervals:
return 0
# Sort intervals based on end time
intervals.sort(key=lambda x: x[1])
# Keep count of non-overlapping intervals
count = 0
# Initialize the end time of the last included interval to the minimum possible
prev_end = float('-inf')
for start, end in intervals:
# If the current interval does not overlap with the last included interval
if start >= prev_end:
# Update the end time of the last included interval
prev_end = end
else:
# Otherwise, we increment the count of intervals to be removed
count += 1
return count
# Example usage
print(eraseOverlapIntervals([[1,2],[2,3],[3,4],[1,3]])) # Output: 1
print(eraseOverlapIntervals([[1,2],[1,2],[1,2]])) # Output: 2
print(eraseOverlapIntervals([[1,2],[2,3]])) # Output: 0
This approach ensures an efficient solution to identify and remove the minimum number of overlapping intervals.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?