Learn / Greedy

Intervals greedy

Sort intervals by end and keep each one that starts at or after the last kept end; everything else must go. To count how many overlap at once, sort the starts and the ends separately and sweep: an arrival adds one, a departure takes one away, and the maximum is the answer.

How to recognise it

  • Intervals must be removed, kept or covered with as few changes as possible.
  • The question is how many things happen at the same time.
  • Arrival and departure times.

Keep the most, remove the fewest

Removing the fewest intervals is the same as keeping the most non-overlapping ones, which is activity selection:

sort by end; kept = 0; lastEnd = -infinity
for (s, e): if s >= lastEnd: kept += 1; lastEnd = e
removed = n - kept

Count what overlaps

sort arrivals; sort departures
i = j = 0
while i < n:
    if arr[i] <= dep[j]: inStation += 1; best = max(best, inStation); i += 1
    else: inStation -= 1; j += 1

The trains do not need to be paired with their own departures: only the order of events matters.

Common mistakes

  • Sorting by start for the removal problem: a long early interval then blocks many short ones.
  • Treating touching intervals the wrong way. Read whether [1, 2] and [2, 3] overlap.

Problems

0 of 2 solved

Check yourself

Fewest removals to leave [[1, 2], [2, 3], [3, 4], [1, 3]] non-overlapping?

Arrivals 900, 940, 950 and departures 910, 1200, 1120. How many platforms?

In the platform sweep, if an arrival equals a departure, which is processed first?