KatInterview

Assign Meetings to Rooms and Find the Most-Used One

Heaps, Sorting & SearchModel answer
MediumModel answerHeaps, Sorting & Searchheapsimulationpriority-queue

Last updated

Simulate meetings being placed into n numbered rooms, delaying them when all rooms are full, then report the room that hosted the most meetings, preferring the lowest index on ties.

Room Allocation Simulation

An office has n meeting rooms numbered 0 to n-1, all empty at the start. You receive a list meetings, where each entry [start, end] is a request to hold a meeting from start (inclusive) to end (exclusive).

Meetings are placed with these rules:

  1. When a meeting is due to start and at least one room is empty, it takes the empty room with the smallest index.
  2. If every room is occupied, the meeting waits and takes the first room that becomes empty. A delayed meeting keeps its original duration (end - start), so it ends later than requested.
  3. If several meetings are waiting at once, the one with the earlier original start time gets the next free room.
  4. Meetings with identical start times are handled in the order they appear in the input.
  5. A room whose meeting ends at time t can host another meeting starting at t.

Return the index of the room that hosted the most meetings. If several rooms tie, return the smallest index.

def busiest_room(n: int, meetings: List[List[int]]) -> int:

Example

n = 2, meetings = [[0, 10], [1, 5], [2, 7], [3, 4]]

  • [0,10] goes to room 0 and runs [0,10).
  • [1,5] goes to room 1 and runs [1,5).
  • [2,7] finds both rooms busy and waits until time 5, when room 1 frees up. Its duration is 5, so it runs [5,10) in room 1.
  • [3,4] waits until time 10, when rooms 0 and 1 are both free. It takes room 0 and runs [10,11).

Room 0 hosted 2 meetings and room 1 hosted 2, so the answer is 0.

Constraints

  • 1 <= n <= 50,000
  • 1 <= meetings.length <= 100,000
  • 0 <= start < end <= 10^9

What to cover in your answer

Explain your approach, justify its correctness, give time and space complexity, mention the edge cases (everything fits in one room, more meetings than rooms, back-to-back meetings), and provide code.

Hints

Hint 1

Handle meetings in order of start time. A stable sort keeps equal-start meetings in input order, which takes care of the tie rule.

Hint 2

Track two groups of rooms: a min-heap of free room indices, and a min-heap of (end_time, room_index) for occupied rooms. Before placing each meeting, move every room with end_time <= start from the busy heap to the free heap.

Hint 3

If no room is free, pop the busy heap's smallest entry. The meeting starts at that end time and lasts (end - start), and the tuple ordering already breaks ties toward the lower room index. Keep a per-room counter and scan it at the end.