Problems › JavaScript › events
How many rooms are needed at peak
A venue schedules sessions across the day. Find the minimum number of rooms so no two overlapping sessions share one.
- Each session has a start and an end in minutes.
- Intervals are half-open: [start, end).
- Sessions that merely touch (one ends exactly when the next starts) do not conflict.
sessionRooms(starts: list<int>, ends: list<int>) → int
Where you start
function sessionRooms(starts, ends) {
}
Worked examples
| Call | Result |
|---|---|
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 JavaScript
function sessionRooms(starts, ends) {
const s = starts.slice().sort((a, b) => a - b);
const e = ends.slice().sort((a, b) => a - b);
let peak = 0, active = 0, 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;
}