Video in progress
You're given meeting time intervals. What is the minimum number of rooms needed to hold them all?
Sort the start and end times separately and walk with two pointers: a start means busy rooms +1, an end means −1, and I remember the maximum. Or I sort by start time and keep a min-heap of end times. Both are O(n log n).
📖 Answer
This is really the question "what is the largest number of intervals open at the same time".
static int minRooms(int[][] meetings) {
int n = meetings.length;
int[] start = new int[n], end = new int[n];
for (int i = 0; i < n; i++) { start[i] = meetings[i][0]; end[i] = meetings[i][1]; }
Arrays.sort(start);
Arrays.sort(end);
int rooms = 0, best = 0, j = 0;
for (int i = 0; i < n; i++) {
while (j < n && end[j] <= start[i]) { j++; rooms--; } // rooms that freed up
rooms++;
best = Math.max(best, rooms);
}
return best;
}
The <= in end[j] <= start[i] matters: the room of a meeting that ends at 10:00 goes to the one that starts at 10:00. If the problem says the intervals are closed rather than half-open, change it to <. Asking the interviewer about this boundary makes a good impression.
The heap version: you sort by start, keep the end times in a PriorityQueue<Integer>, and poll when the earliest-ending one is before the new start. At the end the maximum heap size is the answer. If you also need to know which meeting went into which room, this version is more convenient.
Related problems: merging intervals, the maximum number of non-overlapping intervals (greedy by end time), and whether a new meeting fits into a calendar (TreeMap.floorEntry/ceilingEntry).
Sign up to mark studied questions and save your progress.