Drill

ProblemsTypeScript › events

How many rooms are needed at peak

hardeventsTypeScript

A venue schedules sessions across the day. Find the minimum number of rooms so no two overlapping sessions share one.

sessionRooms(starts: list<int>, ends: list<int>) → int

Solve it in the editor →

Where you start

function sessionRooms(starts: number[], ends: number[]): number {
  
}

Worked examples

CallResult
sessionRooms([10], [20])1
sessionRooms([10,10,10], [20,20,20])3
sessionRooms([10,15], [20,25])2
sessionRooms([10,20,30], [15,25,35])1

Hint

Sort starts and ends independently. Walk both lists with two pointers; the gap between active starts and ends at each step is the current room count — track the peak.

Reference solution in TypeScript
function sessionRooms(starts: number[], ends: number[]): number {
  const s = starts.slice().sort((a, b) => a - b);
  const e = ends.slice().sort((a, b) => a - b);
  let peak = 0;
  let active = 0;
  let j = 0;
  for (let i = 0; i < s.length; i++) {
    active++;
    while (j < e.length && e[j] <= s[i]) {
      active--;
      j++;
    }
    if (active > peak) peak = active;
  }
  return peak;
}

The same problem in another language

More events problems in TypeScript