Remove the fewest intervals so the rest don't overlap. Sort by end time and keep whatever finishes first; every clash after that gets cut.
▼The problem
LeetCode 435 (Medium). Given a list of intervals, return the minimum number of intervals to remove so the rest don't overlap. Intervals that only touch at an endpoint, like [1,2] and [2,3], don't overlap.
Example: [[1,3],[2,4],[3,5],[1,2],[4,6]] → 2.
def erase_overlap_intervals(intervals):
intervals.sort(key=lambda iv: iv[1]) # by end
removed, end = 0, float('-inf')
for s, e in intervals:
if s >= end: # fits: keep it
end = e
else: # overlaps
removed += 1
return removedTRY IT ON LEETCODE ▶The solution
def erase_overlap_intervals(intervals):
intervals.sort(key=lambda iv: iv[1]) # by end
removed, end = 0, float('-inf')
for s, e in intervals:
if s >= end: # fits: keep it
end = e
else: # overlaps
removed += 1
return removedTranscript
Non-overlapping Intervals. Given a list of intervals, remove as few as you can so none of the rest overlap. Intervals that only touch, like one to two and two to three, are fine.
Picture one stage and five shows: one to three, two to four, three to five, one to two, and four to six. Lots of them clash. The most we can keep is three: one to two, two to four and four to six, back to back. Cancel the other two. The answer is two.
The brute force tries every subset of shows and keeps the biggest one with no clashes. Five shows give thirty-two subsets, and each new show doubles that. Thirty shows give over a billion. Far too slow.
Be greedy instead. Which show do you book first? The one that ends earliest. It frees the stage soonest, leaving the most room for the rest. And it's never a mistake: swap the first show of any best schedule for the earliest finisher. It ends no later, so everything after it still fits.
Careful: sorting by start is a trap. A long show, one to ten, starts first and blocks two short ones. Keep it, and you lose both. Sorted by end, the short ones win.
In code, sort by end and remember where the last kept show ends. If a show starts at or after that, keep it and move the end. Otherwise it overlaps: count it as removed.
Let's run it. Sorted by end: one to two, one to three, two to four, three to five, four to six. Book one to two; the stage is free at two. One to three starts at one, too early: remove it. Two to four fits; free at four. Three to five starts too early: remove it. Four to six fits. Two removed.
Sorting takes n log n time, and the sweep is one pass. Beyond the sort, just two numbers: constant extra space.
Sort by end, keep what fits, count the rest. That's Non-overlapping Intervals.