Meeting Rooms II
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
Given meeting time intervals, return the minimum number of rooms needed.
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1Sort meetings by start. When a meeting arrives, which room do you check?
- Hint 2The room that frees up earliest: keep end times in a min-heap.
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
A hotel front desk handing out rooms to guests in order of arrival. For each guest: look at the room that will be vacated soonest. If its guest already left, give the same room; otherwise open another room. The number of rooms ever opened is the answer. The desk only needs the next vacating time, which is exactly what a min-heap hands over.
- The obvious way
Check every time point against all intervals: O(n²).
- The key insight
Sort by start. Keep a min-heap of end times of rooms in use. For each meeting: if the earliest end <= this start, that room is free, so pop it (reuse). Push this meeting's end. The heap size is the number of rooms in use; its largest size is the answer, which equals the final size.
- The algorithm
- Sort meetings by start time.
- Min-heap of end times (rooms in use).
- Heap top <= this start? Pop it: reuse that room.
- Push this end. Answer: heap size at the end.
Watch it run
Example[[0,30],[5,10],[15,20]]
0-30 comes first: open a room. It frees at 30.
rooms busy until: 30
Where people slip
- A meeting ending at 10 and another starting at 10 can share a room: the check is <=.
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
import heapq
def min_meeting_rooms(intervals):
intervals.sort(key=lambda meeting: meeting[0]) # by start time
busy_until = [] # min-heap: when each room in use frees up
for start, end in intervals:
if busy_until and busy_until[0] <= start:
heapq.heappop(busy_until) # that room is free: reuse it
heapq.heappush(busy_until, end)
return len(busy_until)Now close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.