Meeting Rooms II
Difficulty: Medium
You're given a list of meeting times, and you're booking rooms for all of them. Overlapping meetings need separate rooms.
Return the minimum number of rooms so every meeting can happen, with no two overlapping meetings in the same room.
Examples
Input: intervals = [[0,30],[5,10],[15,20]]
Output: 2
[0,30] overlaps both [5,10] and [15,20], but [5,10] and [15,20] don't overlap each other, so 2 rooms are enough.
Input: intervals = [[7,10],[2,4]]
Output: 1
These meetings never overlap, so they can share a single room.
Input: intervals = [[1,5],[8,9],[8,9]]
Output: 2
The two [8,9] meetings happen at the exact same time, so they each need their own room.
Constraints
1 <= intervals.length <= 10^4
intervals[i].length == 2
0 <= start < end <= 10^6
Approach
The direct way: at each meeting's start time t, count the meetings in progress (start <= t < end). The largest count is the minimum number of rooms.
Faster: put all start times and all end times in two sorted lists and sweep them like a timeline. Before admitting each new meeting, check whether an earlier meeting has already ended:
- If so, reuse its room.
- If not, open a new room.
Track the rooms in use and their peak. The peak is the answer, found in one pass over the sorted events.
Solutions
Brute Force — Count Active Meetings at Each Start Time
At each meeting's start time, count the meetings in progress (start at or before it, end after it). The largest count is the busiest moment, and the number of rooms needed.
function minMeetingRooms(intervals) {
let maxRooms = 0;
for (let i = 0; i < intervals.length; i++) {
const t = intervals[i][0];
let count = 0;
for (let j = 0; j < intervals.length; j++) {
if (intervals[j][0] <= t && t < intervals[j][1]) {
count++;
}
}
maxRooms = Math.max(maxRooms, count);
}
return maxRooms;
}Time: O(n^2) — for every meeting, rescan all meetings · Space: O(1) extra space
Optimal — Sweep Sorted Starts and Ends
Sort the start times and end times into two arrays, and walk each with its own pointer. At each step, compare the current start with the earliest remaining end:
- Start is before that end: a new room is needed (rooms in use + 1).
- Start is at or after that end: a meeting has finished, so its room is freed (rooms in use - 1, move to the next end).
The highest "rooms in use" seen is the answer.
function minMeetingRooms(intervals) {
const n = intervals.length;
if (n === 0) return 0;
const starts = intervals.map((iv) => iv[0]).sort((a, b) => a - b);
const ends = intervals.map((iv) => iv[1]).sort((a, b) => a - b);
let roomsInUse = 0;
let maxRooms = 0;
let startPtr = 0;
let endPtr = 0;
while (startPtr < n) {
if (starts[startPtr] < ends[endPtr]) {
roomsInUse++;
startPtr++;
} else {
roomsInUse--;
endPtr++;
}
maxRooms = Math.max(maxRooms, roomsInUse);
}
return maxRooms;
}Time: O(n log n) — dominated by sorting the starts and ends · Space: O(n) for the two sorted arrays