14/42
Part 4 of 8 · The sweepLearn and do

The sweep turns each interval into +1 at its start and -1 at its end

Checking every moment works only while the times are small whole numbers. A sweep looks only at the moments where something changes.

def most_at_once(reservations):
    events = []
    for start, end in reservations:
        events.append((start, 1))
        events.append((end, -1))
    # by time, and at one time -1 sorts before +1
    events.sort()
    now = most = 0
    for _, change in events:
        now += change
        most = max(most, now)
    return most


R = [(1, 4), (2, 5), (3, 4), (4, 7), (5, 8)]
print(most_at_once(R))
3

The sweep looks at moments instead of pairs. Picture a line that moves from left to right across the timeline. Each start it crosses adds 1 to a running count, and each end takes 1 off. The count is how many reservations are open right there, and the largest count is the answer:

The sweep line at 4
the sweep line
(1, 4) ends at 4
(2, 5)
(3, 4) ends at 4
(4, 7) starts at 4
(5, 8)
02468

Open just after each time from 1: 1, 2, 3, 2, 2, 2, 1, 0. The most is 3, from 3 to 4.

The peak is 3, at time 3. The cost is the sort: O(n log n) time, and O(n) memory for the 2n events.

In the editor, write open_after(res): build the +1 and -1 events, sort them, and record in counts how many reservations are open after each event.