Skip to content
DSA Patterns
Menu
Language
IntervalsLC #2534 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Meeting Rooms II

Problem (restated)

Given meeting time intervals, find the minimum number of conference rooms required.

Intuition

Sort starts and ends; sweep: start increments rooms, end frees; track peak.

Approaches

Sweep line

Unverified
Time O(n log n)Space O(n)

Idea. Two pointers on sorted starts/ends.

Walkthrough. [[0,30],[5,10],[15,20]] → 2 rooms.

Trade-offs. Sweep vs min-heap of end times.

Solution
export function minMeetingRooms(intervals: number[][]): number {
  const starts = intervals.map((x) => x[0]!).sort((a, b) => a - b);
  const ends = intervals.map((x) => x[1]!).sort((a, b) => a - b);
  let i = 0, j = 0, cur = 0, peak = 0;
  while (i < starts.length) {
    if (starts[i]! < ends[j]!) {
      cur++;
      peak = Math.max(peak, cur);
      i++;
    } else {
      cur--;
      j++;
    }
  }
  return peak;
}
export function minMeetingRooms(intervals: number[][]): number {
  const starts = intervals.map((x) => x[0]!).sort((a, b) => a - b);
  const ends = intervals.map((x) => x[1]!).sort((a, b) => a - b);
  let i = 0, j = 0, cur = 0, peak = 0;
  while (i < starts.length) {
    if (starts[i]! < ends[j]!) {
      cur++;
      peak = Math.max(peak, cur);
      i++;
    } else {
      cur--;
      j++;
    }
  }
  return peak;
}

Template connection

Min-rooms sweep on two sorted arrays, starts and ends. A start that arrives before the next end opens a room. An end that arrives at or before the next start closes one. The peak number of open rooms is the answer.

Reflection

  • A start is +1 and an end is −1. At the same time, processing the start before the end counts an extra room.
  • The answer is the highest counter on the sweep. Three nested meetings need 3 rooms.
  • An empty list is 0. Meetings that only touch share a room.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 7
1/7

Meeting rooms: convert intervals to enter/exit events, then sweep left to right.

[0,30]
[5,10]
[15,20]
Stateactive=0peak=0

events = start +1, end -1

Key:CurrentActive rangeMatchSettled