Remove the fewest intervals needed so that all remaining intervals are compatible in time.
Problem
Input. A list intervals of numeric pairs [start, end], each satisfying start < end.
Output. Return the smallest number of intervals to remove so that no remaining intervals overlap.
Rules. Touching is compatible: one interval may start exactly when another ends. Count removed occurrences, including repeated intervals, rather than removed duration. Return only the removal count. The reference may reorder the input; an empty list returns zero.
Example. [[1, 3], [3, 5], [2, 4], [5, 7]] returns 1.
Removing [2, 4] leaves three compatible intervals, including two pairs with touching endpoints.
Picture
Sort by finish: [1,3], [2,4], [3,5], [5,7].
Keeping [1,3] leaves [3,5] available.
Choosing [2,4] first would block [3,5] without enabling any later choice unavailable after finish 3.
Take an optimal nonempty schedule. Replace its first interval with the earliest-finishing candidate. Every later start still reaches that earlier finish, so the replacement preserves the schedule’s count. Repeat on the compatible suffix; an optimal solution can therefore follow every greedy choice.
Minimum removals equal total intervals minus maximum compatible cardinality. Unlike union, this objective may discard covered time.
Problem trace
The earlier finishing interval leaves at least as much room for later choices
- max
- 7
- example
- intervals = [[1,3], [3,5], [2,4], [5,7]]
- sorted by end
- [1,3], [2,4], [3,5], [5,7]
- comparison
- not shown→1 < -inf: false
- last end
- -inf→3
- decision
- not shown→keep [1,3]
- comparison
- 1 < -inf: false→2 < 3: true
- removed
- 0→1
- decision
- keep [1,3]→remove [2,4]
- comparison
- 2 < 3: true→3 < 3: false
- last end
- 3→5
- decision
- remove [2,4]→keep [3,5]
- comparison
- 3 < 3: false→5 < 5: false
- last end
- 5→7
- decision
- keep [3,5]→keep [5,7]
- kept
- not shown→3
- result
- not shown→1
- comparison
- 5 < 5: false→not shown
- Recognize it
- The task asks for the fewest removals needed to leave non-overlapping ranges, which is equivalent to keeping the largest compatible subset.
- Keep true
- After each candidate, the kept intervals do not overlap, last_end is the end of the latest kept interval, and the greedy choices leave at least as much future room as any alternative of the same size.
- Reuse it
- When selecting the most compatible time ranges, an earlier finishing accepted choice never blocks a range that a later-finishing choice could keep; reuse this exchange argument for activity and reservation scheduling.
Reference drawing
Problem trace
The earlier finishing interval leaves at least as much room for later choices
Execution trace
- max
- 7
- example
- intervals = [[1,3], [3,5], [2,4], [5,7]]
- sorted by end
- [1,3], [2,4], [3,5], [5,7]
- comparison
- not shown→1 < -inf: false
- last end
- -inf→3
- decision
- not shown→keep [1,3]
- comparison
- 1 < -inf: false→2 < 3: true
- removed
- 0→1
- decision
- keep [1,3]→remove [2,4]
- comparison
- 2 < 3: true→3 < 3: false
- last end
- 3→5
- decision
- remove [2,4]→keep [3,5]
- comparison
- 3 < 3: false→5 < 5: false
- last end
- 5→7
- decision
- keep [3,5]→keep [5,7]
- kept
- not shown→3
- result
- not shown→1
- comparison
- 5 < 5: false→not shown
- Recognize it
- The task asks for the fewest removals needed to leave non-overlapping ranges, which is equivalent to keeping the largest compatible subset.
- Keep true
- After each candidate, the kept intervals do not overlap, last_end is the end of the latest kept interval, and the greedy choices leave at least as much future room as any alternative of the same size.
- Reuse it
- When selecting the most compatible time ranges, an earlier finishing accepted choice never blocks a range that a later-finishing choice could keep; reuse this exchange argument for activity and reservation scheduling.
Keep [1,3], reject [2,4], then keep touching [3,5] and [5,7].
last_end changes only after acceptance.
Rejecting an overlapping range must not move that boundary.
Code
def erase_overlap_intervals(intervals: list[list[int]]) -> int:
removed = 0
last_end = float("-inf")
for start, end in sorted(intervals, key=lambda interval: interval[1]):
if start < last_end:
removed += 1
else:
last_end = end
return removed
The scan retains scalars, but Python’s sorted list and sorting workspace use storage.
Whole-function time is ; input rows remain unchanged.
Empty input returns 0.
Failure Check
Start-order selection can keep [0,10] while losing three compatible short ranges [1,2], [2,3], [3,4].
Updating last_end after rejecting [2,4] would incorrectly block [3,5].
The exchange proves cardinality, not maximum total weight.
Change to Witness Output
New task: Return a maximum compatible subset.
Picture and change: Append a copied range at each accepted transition. The eligibility test and exchange proof stay unchanged.
def compatible_intervals(intervals):
kept, last_end = [], float("-inf")
for start, end in sorted(intervals, key=lambda interval: interval[1]):
if start >= last_end:
kept.append([start, end])
last_end = end
return kept
Check: The source example returns [[1,3],[3,5],[5,7]].
Its count must equal input length minus reference removals.
Adjacent chosen ranges must satisfy previous_end <= next_start.
Output adds storage proportional to the kept count; ties need not produce a unique witness.
Use when: The choices themselves must be shown.
Change to Unequal Values
New task: Maximize total weight of compatible (start,end,weight) ranges.
Choosing nothing remains allowed.
Picture and change: End-sort and find each interval’s last compatible prefix. Compare skipping it with its weight plus that prefix optimum. This uses compatible prefix optima, not the equal-cardinality theorem.
from bisect import bisect_right
def maximum_interval_weight(intervals):
ordered = sorted(intervals, key=lambda interval: interval[1])
ends = [end for start, end, weight in ordered]
best = [0] * (len(ordered) + 1)
for index, (start, end, weight) in enumerate(ordered):
compatible = bisect_right(ends, start, 0, index)
best[index + 1] = max(best[index], best[compatible] + weight)
return best[-1]
Check: [[0,3,100],[0,1,1],[1,2,1],[2,3,1]] returns 100.
Three weight-one intervals lose to one weight-100 interval despite their larger count.
Binary search includes earlier ends equal to the current start, preserving touching compatibility.
The weighted function uses scalar work and storage, returning value rather than indices.
Use when: Interval weights replace equal-count value.
Transfer Check
Why does union extend a maximum end while this algorithm prefers an earlier finish?
Answer
Union preserves all covered points. Scheduling may discard coverage to leave room for more choices. The objectives justify different state updates.