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

A min-heap of end times and two sorted lists give the same count

A min-heap of the end times of the rooms in use gets the same answer. The heaps lesson's version pops every end at or before each start, then pushes the new end. The most end times the heap ever holds at once is the answer. Its ends[0] <= start is the same tie rule as ends going first here.

A third form skips the tuples. Sort the starts and the ends as two lists of plain numbers, and walk both. Here are both, the heap first:

import heapq


def most_at_once_heap(meetings):
    # end times of the rooms in use
    ends, most = [], 0
    for start, end in sorted(meetings):
        while ends and ends[0] <= start:
            heapq.heappop(ends)
        heapq.heappush(ends, end)
        most = max(most, len(ends))
    return most


def most_at_once_two_lists(meetings):
    starts = sorted(s for s, _ in meetings)
    ends = sorted(e for _, e in meetings)
    now = most = j = 0
    for s in starts:
        # ends at or before this start come first
        while ends[j] <= s:
            j += 1
            now -= 1
        now += 1
        most = max(most, now)
    return most


for meetings in (R, [(1, 4), (4, 7), (7, 9)]):
    print(most_at_once(meetings), most_at_once_heap(meetings), most_at_once_two_lists(meetings))
3 3 3
1 1 1

All three agreed on 100,000 random meetings, built with random.Random(7). Each starts at a random hour from 0 to 100,000 and lasts a random 1 to 200 hours, or 1 to 2,000:

Longest meetingAnswerHeap of end timesEvents as tuplesTwo sorted lists
20014147.4 ms75.4 ms37.4 ms
2,0001,08953.5 ms84.6 ms40.3 ms

Best of 5 runs, Python 3.12, on the laptop these numbers come from. All three are O(n log n). The two lists sort plain integers, which is cheaper than sorting 200,000 tuples.

Reach for the events version when events carry more than plus or minus one. A reservation for 3 machines is +3 and -3, and different kinds of event can share one sorted list.

When times are small integers, like the 1,440 minutes of a day, you can skip the sort. Keep a list of counts, one slot per minute. Add 1 at each start, subtract 1 at each end, and keep a running sum: O(n + T) for T time slots.

In the editor, each reservation is a half-open (start, end, k) that holds k machines. In machines_needed(res), write the events, +k at the start and -k at the end, and the sweep below them does the rest.