21/40
Part 5 of 8 · Merging and schedulingLearn and do

Only the room that frees up soonest matters, so keep the end times in a heap

The scan is correct, and it checks every room for every meeting: O(n × r) for n meetings and r rooms. But you never need to know which room is free. You only need to know whether the one that frees up soonest is. So keep the end times of the rooms in use in a heap, ends:

  1. Take the meetings in start order.
  2. Pop every end time at or before the meeting's start. Those rooms are free again.
  3. Push the meeting's own end.

The most end times the heap ever holds at once is the answer. Here's that on the same six meetings:

MeetingPopped, ended by its startends after the pushRooms in use
9 to 10[10]1
9 to 11[10, 11]2
10 to 1110[11, 11]2
10 to 12[11, 11, 12]3
11 to 1311, 11[12, 13]2
12 to 1412[13, 14]2

Three rooms, at 10. The third row is the tie rule doing its job. The meeting that ends at 10 gives its room to the one that starts at 10, because 10 <= 10. On the line of hours, those two bars meet but don't overlap.

On 100,000 random meetings, starting anywhere from 0 to 100,000 and lasting up to 200 or up to 2,000, the two answers agreed. The heap version took 48.4 ms when they needed 135 rooms, and 54.5 ms when they needed 1,141. The scan took 111.9 ms and 941.2 ms. Its cost grows with the rooms, and the heap's barely does.

In the editor, write the loop of rooms_needed(meetings): take the meetings in start order, pop every end time in ends at or before the start, push the meeting's end, and keep the most rooms in use in most.