Algorithms · Level 2 Heaps

Heaps: Meeting Rooms

Work out how many meeting rooms a day needs with a heap of end times, so the room that frees up first is always on top.

  • heap[0] is the smallest item
  • heappush and heappop in O(log n)
  • ending at 10:00 frees a 10:00 slot

A heap keeps its smallest item at heap[0]; heappush and heappop cost O(log n). Here it holds the end times of rooms in use, so the room that frees up first is on top. Trap: a meeting ending at 10 frees its room for one starting at 10.

import heapq
ends = []
heapq.heappush(ends, 11)
heapq.heappush(ends, 9)
ends[0]  # 9: the earliest end
heapq.heappop(ends)  # 9

Write rooms_needed(meetings): the fewest rooms so that no two (start, end) meetings in the same room overlap. Example: rooms_needed([(9, 11), (10, 12), (11, 13)]) → 2. A meeting ending at 10 and one starting at 10 can share a room.

solution.py
Test Suites Pending
Output