def eraseOverlapIntervals(intervals): intervals.sort(key=lambda x: x[1]) count = 0 end = float('-inf') for interval in intervals: if interval[0] >= end: end = interval[1] else: count += 1 return count intervals = [[1,3],[2,4],[3,5],[7,8]] print(eraseOverlapIntervals(intervals))
The code sorts intervals by their end time. It then iterates and counts intervals that overlap with the last chosen interval. Here, only one interval needs removal to avoid overlap.
def eraseOverlapIntervals(intervals): intervals.sort(key=lambda x: x[1]) count = 0 end = float('-inf') for interval in intervals: if interval[0] >= end: end = interval[1] else: count += 1 return count intervals = [[1,10],[2,3],[3,4],[4,5]] print(eraseOverlapIntervals(intervals))
After sorting by end time to [[2,3],[3,4],[4,5],[1,10]], the code keeps [2,3], [3,4], [4,5] (non-overlapping as start >= previous end), skips [1,10], removes 1 interval.
def eraseOverlapIntervals(intervals): intervals.sort(key=lambda x: x[0]) count = 0 end = float('-inf') for interval in intervals: if interval[0] >= end: end = interval[1] else: count += 1 return count intervals = [[1,2],[2,3],[1,3]] print(eraseOverlapIntervals(intervals))
The code sorts by start time instead of end time, but still counts overlaps correctly. It outputs 1 because one interval overlaps.
Sorting by end time helps pick intervals that free up space earliest, allowing more intervals to fit without overlap, minimizing removals.
def eraseOverlapIntervals(intervals): intervals.sort(key=lambda x: x[1]) count = 0 end = float('-inf') for interval in intervals: if interval[0] >= end: end = interval[1] else: count += 1 return count intervals = [[0,30],[5,10],[15,20],[25,35],[27,40],[40,50]] print(eraseOverlapIntervals(intervals))
After sorting by end time to [[5,10],[15,20],[0,30],[25,35],[27,40],[40,50]], keeps [5,10], [15,20], [25,35], [40,50]; removes [0,30] and [27,40], totaling 2 removals.