Skip to content
mlmentorship

Track active end times to find peak room demand

Count simultaneous half-open meetings, prove the minimum room count, then change endpoint occupancy or return reusable room IDs.

Published · 18 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

Track active end times to find peak room demand

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

Problem

Input. A list intervals of integer meeting pairs [start, end], each satisfying start < end. Output. Return the smallest number of rooms that accommodates every meeting at its specified time. Rules. Each meeting occupies a half-open interval [start, end) and needs one room throughout. A room may be reused exactly when its previous meeting ends. Meetings cannot move in time. Empty input returns zero; zero-duration meetings are outside this contract. Example. [[0, 30], [5, 10], [5, 15], [20, 25]] returns 3 because three meetings overlap at time 5. For [[0, 5], [5, 10]], return 1.

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

Before each start, pop every ended meeting; then push the new end and record the largest heap size.

Problem trace

Peak overlap determines room demand, not the final heap size

Input and goalFind the smallest number of rooms needed for all meetings.
Initialize the active heapSort meetings by start. Begin with an empty heap and zero peak.
empty heapempty
Original heap grid
root -minimum-left -right -
exampleintervals = [[0,30], [5,10], [5,15], [20,25]]heapArray[]heapMeaningretained end times; cleanup removes expired meetingsnextMeeting[0,30]mostRooms0
minimum
(0, 0)
example
intervals = [[0,30], [5,10], [5,15], [20,25]]
heap array
[]

Recognize it
The question asks for the maximum number of simultaneous intervals, and meetings that end before the next start release reusable capacity.
Keep true
Immediately before pushing a meeting, the heap contains exactly the end times greater than its start; after pushing, heap size equals active rooms and most_rooms is the largest size seen.
Reuse it
For capacity over time, sweep arrivals and keep active expirations ordered by the next one to finish; this transfers to server concurrency, platform usage, and resource reservation.
Sort meetings by start. Begin with an empty heap and zero peak. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why are three rooms required even though only two end times remain in the final heap?
Full interview answer 18 min read

Find the fewest rooms needed to hold every meeting without putting overlapping meetings in the same room.

Problem

Input. A list intervals of integer meeting pairs [start, end], each satisfying start < end.

Output. Return the smallest number of rooms that accommodates every meeting at its specified time.

Rules. Each meeting occupies a half-open interval [start, end) and needs one room throughout. A room may be reused exactly when its previous meeting ends. Meetings cannot move in time. Empty input returns zero; zero-duration meetings are outside this contract.

Example. [[0, 30], [5, 10], [5, 15], [20, 25]] returns 3 because three meetings overlap at time 5. For [[0, 5], [5, 10]], return 1.

Picture

Process starts in sorted order. The heap stores end times for meetings still active at the current start. Its root is the earliest end, not the end of the most recently added meeting.

Next meetingReleased endsActive end times after insertionLargest count
[0,30]None301
[5,10]None10,302
[5,15]None10,15,303
[20,25]10, then 1525,303

The table lists active values in order for inspection; heap storage need not be fully sorted. Before time 20, release both expired meetings while retaining the meeting ending at 30. Current occupancy becomes two, but the earlier peak remains three.

Any simultaneous meetings require distinct rooms, giving a lower bound on capacity. Reusing a released room, or allocating one when none is free, constructs a schedule meeting that bound.

Problem trace

Separate occupancy checkpoints: peak demand survives a smaller final heap

Worked example: the peak room demand survives a smaller final active heapNear the middle checkpoint, two meeting intervals overlap. Later only one remains active, but the earlier overlap still requires two rooms. Removing finished meetings changes the current occupancy, not the saved peak.The saved room peak survives asmaller final active heapThree ordered occupancycheckpointsBlue: current; green: saved best12320Checkpoint numberCurrent: 1, 2, 1Saved: 1, 2, 2
Read it this way: Near the middle checkpoint, two meeting intervals overlap. Later only one remains active, but the earlier overlap still requires two rooms. Removing finished meetings changes the current occupancy, not the saved peak. Can the smaller occupancy at the last checkpoint retroactively eliminate the earlier need for two rooms?
Reference drawing

Problem trace

Peak overlap determines room demand, not the final heap size

Worked example: the peak room demand survives a smaller final active heapNear the middle checkpoint, two meeting intervals overlap. Later only one remains active, but the earlier overlap still requires two rooms. Removing finished meetings changes the current occupancy, not the saved peak.The saved room peak survives asmaller final active heapThree ordered occupancycheckpointsBlue: current; green: saved best12320Checkpoint numberCurrent: 1, 2, 1Saved: 1, 2, 2
Execution trace
Input and goalFind the smallest number of rooms needed for all meetings.
Initialize the active heapSort meetings by start. Begin with an empty heap and zero peak.
empty heapempty
Original heap grid
root -minimum-left -right -
exampleintervals = [[0,30], [5,10], [5,15], [20,25]]heapArray[]heapMeaningretained end times; cleanup removes expired meetingsnextMeeting[0,30]mostRooms0
minimum
(0, 0)
example
intervals = [[0,30], [5,10], [5,15], [20,25]]
heap array
[]

Recognize it
The question asks for the maximum number of simultaneous intervals, and meetings that end before the next start release reusable capacity.
Keep true
Immediately before pushing a meeting, the heap contains exactly the end times greater than its start; after pushing, heap size equals active rooms and most_rooms is the largest size seen.
Reuse it
For capacity over time, sweep arrivals and keep active expirations ordered by the next one to finish; this transfers to server concurrency, platform usage, and resource reservation.
Sort meetings by start. Begin with an empty heap and zero peak. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why are three rooms required even though only two end times remain in the final heap?
Read it this way: Near the middle checkpoint, two meeting intervals overlap. Later only one remains active, but the earlier overlap still requires two rooms. Removing finished meetings changes the current occupancy, not the saved peak. Can the smaller occupancy at the last checkpoint retroactively eliminate the earlier need for two rooms?

Code

import heapq

def min_meeting_rooms(intervals: list[list[int]]) -> int:
   end_times: list[int] = []
   most_rooms = 0

   for start, end in sorted(intervals):
      while end_times and end_times[0] <= start:
         heapq.heappop(end_times)
      heapq.heappush(end_times, end)
      most_rooms = max(most_rooms, len(end_times))
   return most_rooms

Each end enters and leaves the heap at most once. Sorting and heap updates take scalar work and storage, including the sorted input copy. The original list stays unchanged; empty input returns 0.

Failure Check

Returning the final heap size gives 2, missing the earlier demand for three rooms. Replacing while with if leaves expired 15 before time 20, breaking this exact-active-population invariant. A room-allocation algorithm may use another invariant; do not describe its retained heap as the current active population.

Change Endpoint Occupancy

New task: Both endpoints occupy the room at their exact timestamp.

Picture and change: Release an end only when it is strictly earlier than the new start. The peak-count argument stays unchanged.

import heapq

def closed_meeting_rooms(intervals):
   active, peak = [], 0
   for start, end in sorted(intervals):
      while active and active[0] < start:
         heapq.heappop(active)
      heapq.heappush(active, end)
      peak = max(peak, len(active))
   return peak

Check: [[0,1],[1,2]] needs two rooms because both meetings occupy time 1. The half-open reference needs one. Positive duration remains required; this change does not introduce a zero-duration policy.

Use when: The occupancy contract makes touching endpoints conflict.

Change to a Room Assignment

New task: Return room IDs in original input order, together with the minimum allocated count.

Picture and change: Store (end,room) in the active heap and released IDs in a second min-heap. Keep original indices while sorting, and allocate a new ID only when no released ID exists.

import heapq

def assign_meeting_rooms(intervals):
   active, free = [], []
   assigned = [None] * len(intervals)
   room_count = 0
   for index, (start, end) in sorted(enumerate(intervals), key=lambda item: item[1]):
      while active and active[0][0] <= start:
         ended, room = heapq.heappop(active)
         heapq.heappush(free, room)
      if free:
         room = heapq.heappop(free)
      else:
         room = room_count
         room_count += 1
      assigned[index] = room
      heapq.heappush(active, (end, room))
   return room_count, assigned

Check: The source example returns (3,[0,1,2,1]). The last meeting reuses room 1; meetings sharing any room must satisfy previous_end <= next_start. Both variants retain work and storage under scalar endpoint costs.

Use when: The capacity answer needs a concrete assignment witness.

Transfer Check

Why can one last_end solve compatible interval selection but not represent this active population?

Answer

Several concurrent meetings expire at different times. Room demand needs their population and next expiration, not one chosen interval’s compatibility frontier.