Data Structures19 sections · 729 units
Open in Course

Meeting Rooms II: Heap Approach

Track ending times

Alternative: use a min-heap of ending times.

function minMeetingRooms(intervals)
    sort intervals by start time
    heap := min-heap of end times

    for interval in intervals
        if heap not empty and heap.peek() <= interval.start then
            // Reuse a room
            heap.pop()
        heap.push(interval.end)

    return heap.size()

The heap tracks rooms in use. When a meeting starts:

  • If any room is free (earliest end time \leq current start), reuse it
  • Otherwise, add a new room

The heap size at the end is the maximum rooms needed.

Time: O(nlogn)O(n \log n). Space: O(n)O(n).