Python coding

Fewest meeting rooms

Each meeting is a pair [start, end] with start < end. Given a list of meetings, return the fewest rooms needed so that no two meetings overlap in the same room. A meeting that ends at time t frees its room for one that starts at t.

The list is not sorted and may be empty.

Besides the tests, one large input (5,500 meetings) with a ~450 ms limit (scaled to your device's speed): brute force won't pass.

  • min_rooms([[0,30],[5,10],[15,20]]) → 2
  • min_rooms([[7,10],[2,4]]) → 1
  • min_rooms([[1,5],[5,8]]) → 1
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Only how many meetings run at the same moment matters. Turn each meeting into two events: +1 when it starts, −1 when it ends.

Hint 2

Sort the events by time and keep a running sum; its peak is the answer. At equal times, process −1 before +1 so a freed room is reused.

Solution and why it works
pythonO(n log n) · O(n)
def min_rooms(meetings: list[list[int]]) -> int:
    events = []
    for start, end in meetings:
        events.append((start, 1))
        events.append((end, -1))
    events.sort()
    rooms = peak = 0
    for _, delta in events:
        rooms += delta
        peak = max(peak, rooms)
    return peak

The rooms needed equal the most meetings running at once, so sweep the events in time order: +1 at a start, −1 at an end, and keep the running sum's peak. Sorting (time, delta) tuples breaks ties for you: −1 sorts before +1, so [1,5] and [5,8] share one room. Process starts first instead and those two would wrongly need two rooms.