Greedy Algorithms8 sections · 316 units
Open in Course

Meeting Rooms II - Implementation

The code

Here is the solution using event sweep:

function minMeetingRooms(intervals)
 events := []
 for each interval in intervals
 events.add((interval.start, +1))
 events.add((interval.end, -1))
 sort events by time (if tie, process -1 before +1)
 rooms := 0
 maxRooms := 0
 for each (time, delta) in events
 rooms := rooms + delta
 maxRooms := max(maxRooms, rooms)
 return maxRooms

Time: O(nlogn)O(n \log n). Space: O(n)O(n) for events array.

The tie-breaking rule matters: if a meeting ends at time tt and another starts at tt, the ending frees a room before the new one needs it.