sagelearnai

Meeting Rooms II

Difficulty: Medium · Pattern: Intervals · LeetCode #253

Given meeting intervals [start, end], return the minimum number of conference rooms required. A meeting can start in a room at the exact moment another meeting there ends.

Examples

text
[[0,30],[5,10],[15,20]]  →  2
[[7,10],[2,4]]           →  1

Hints

  1. The answer is the maximum number of meetings happening at the same moment.
  2. Sort the starts and the ends separately and sweep through time.

Approach

Two sorted arrays (sweep line):

text
starts = sorted(s), ends = sorted(e); j = 0; rooms = 0
for s in starts:
    if s >= ends[j]: j += 1        # a meeting ended: reuse its room
    else: rooms += 1               # need a new room

Which meeting ended doesn't matter, only how many have ended by time s. >= lets back-to-back meetings share a room.

Heap version: sort by start and keep a min-heap of end times. Pop if the earliest end is ≤ the current start, then push the current end. The heap's maximum size is the answer. Both are O(n log n).

Complexity

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

Python solution
def minMeetingRooms(intervals):
    starts = sorted(i[0] for i in intervals)
    ends = sorted(i[1] for i in intervals)
    rooms = j = 0
    for s in starts:
        if s >= ends[j]:
            j += 1
        else:
            rooms += 1
    return rooms
JavaScript solution
function minMeetingRooms(intervals) {
  const ev = [];
  for (const [s, e] of intervals) ev.push([s, 1], [e, -1]);
  ev.sort((a, b) => a[0] - b[0] || a[1] - b[1]);  // ends (-1) before starts (+1) at the same time
  let cur = 0, best = 0;
  for (const [, d] of ev) { cur += d; best = Math.max(best, cur); }
  return best;
}