Meeting rooms

Lesson 12.4 · Medium · Sweep with end times · 10 min · by Vinay C

We'll cover the following

Given meeting times, find the minimum number of rooms needed so no two meetings in a room overlap.

Watch it run

Press Play or Step to walk through the example, or change the input and press Run. Each frame says what the algorithm does and why.

14 items · 15 steps
new room0-300
2-91
5-102
8-143
12-254
15-205
18-276
22-357
28-408
33-459
36-4810
40-5011
44-5512
50-6013

Meeting 0-30. No rooms yet, so open one.

room end times [30] · rooms 1

1 / 15

The idea

Complexity

TimeSpaceWhy
O(n log n)O(n)Sort, then one heap operation per meeting.

In Python

import heapq
def min_rooms(intervals):
    intervals.sort()
    ends = []                                  # min-heap of room end times
    for s, e in intervals:
        if ends and ends[0] <= s: heapq.heapreplace(ends, e)   # reuse
        else: heapq.heappush(ends, e)                          # new room
    return len(ends)

Summary: say it in the interview

  • Process meetings by start time and track when each room becomes free. If the earliest-free room is free by the new start, reuse it. Otherwise open a new room. A min-heap of end times finds that earliest room fast.
  • Time O(n log n), space O(n). Sort, then one heap operation per meeting.