SDE & MLE Prep

2402. Meeting Rooms III

Problem

Rooms 0…n − 1 host meetings[i] = [start, end) (all starts distinct). Each meeting takes the free room with the lowest number; if none is free, it waits for the earliest-freed room and keeps its duration, and waiting meetings are served in order of original start. Return the room that hosted the most meetings (ties: lowest number).

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

Constraints: n ≤ 100; up to 10⁵ meetings.

Process meetings by start time with two min-heaps: free rooms by number and busy rooms by (end time, room). Before each meeting, release rooms that have ended. If a room is free, use the lowest-numbered one; otherwise wait for the earliest-ending room (lowest number on ties) and delay the meeting, keeping its duration. Count uses per room.

Complexity: O(m log m + m log n).

class Solution:
    def mostBooked(self, n: int, meetings: List[List[int]]) -> int:
        free, busy, count = list(range(n)), [], [0] * n
        for s, e in sorted(meetings):
            while busy and busy[0][0] <= s:
                heappush(free, heappop(busy)[1])
            if free:
                room = heappop(free)
                heappush(busy, (e, room))
            else:
                end, room = heappop(busy)
                heappush(busy, (end + e - s, room))
            count[room] += 1
        return count.index(max(count))