Skip to content
mlmentorship

Keep the earliest finishing compatible range to preserve future room

Prove maximum compatible cardinality by exchange, then request a witness or change to weighted interval selection.

Published · 10 min read ·Core ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Keep the earliest finishing compatible range to preserve future room

Explain the mechanism, why it works, when it fails, and one alternative.

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.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Sort by end time; keep a candidate exactly when its start reaches the last kept end.

Problem trace

The earlier finishing interval leaves at least as much room for later choices

Worked example: the earlier finish preserves more future choicesKeeping (1,3) permits the next interval (3,4). Keeping (1,5) blocks it, despite the identical starting point.An earlier retained finish leaves thenext interval availableKept [1,3); next [3,4)134Next begins as the kept intervalends: fitsKept [1,5); next [3,4)1534Next begins before the kept intervalends: overlap
Read it this way: Keeping (1,3) permits the next interval (3,4). Keeping (1,5) blocks it, despite the identical starting point. Which future interval becomes impossible if the retained finish moves from three to five?
Full interview answer 10 min read

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

Input and goalFind the fewest ranges to remove so the rest do not overlap.
Initialize after sortingSorting by end gives [1,3], [2,4], [3,5], [5,7]. Start with last_end=-inf and removed=0.
[1,3]
[2,4]
[3,5]
[5,7]
exampleintervals = [[1,3], [3,5], [2,4], [5,7]]sortedByEnd[1,3], [2,4], [3,5], [5,7]lastEnd-infremoved0
max
7
example
intervals = [[1,3], [3,5], [2,4], [5,7]]
sorted by end
[1,3], [2,4], [3,5], [5,7]

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.
Sorting by end gives [1,3], [2,4], [3,5], [5,7]. Start with last_end=-inf and removed=0. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why is keeping [1,3] at least as good as keeping the overlapping [2,4] for all later choices?
Reference drawing

Problem trace

The earlier finishing interval leaves at least as much room for later choices

Worked example: the earlier finish preserves more future choicesKeeping (1,3) permits the next interval (3,4). Keeping (1,5) blocks it, despite the identical starting point.An earlier retained finish leaves thenext interval availableKept [1,3); next [3,4)134Next begins as the kept intervalends: fitsKept [1,5); next [3,4)1534Next begins before the kept intervalends: overlap
Execution trace
Input and goalFind the fewest ranges to remove so the rest do not overlap.
Initialize after sortingSorting by end gives [1,3], [2,4], [3,5], [5,7]. Start with last_end=-inf and removed=0.
[1,3]
[2,4]
[3,5]
[5,7]
exampleintervals = [[1,3], [3,5], [2,4], [5,7]]sortedByEnd[1,3], [2,4], [3,5], [5,7]lastEnd-infremoved0
max
7
example
intervals = [[1,3], [3,5], [2,4], [5,7]]
sorted by end
[1,3], [2,4], [3,5], [5,7]

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.
Sorting by end gives [1,3], [2,4], [3,5], [5,7]. Start with last_end=-inf and removed=0. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why is keeping [1,3] at least as good as keeping the overlapping [2,4] for all later choices?
Read it this way: Keeping (1,3) permits the next interval (3,4). Keeping (1,5) blocks it, despite the identical starting point. Which future interval becomes impossible if the retained finish moves from three to five?

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.