DSA Heaps

Meeting Rooms III

With fixed n rooms, schedule meetings preferring the lowest-numbered free room — return the busiest room.

Hard
Time O(m log m + m log n) Space O(n)
LeetCode
7 min read
heaps

Problem#

You have n rooms numbered 0..n-1 and a list of meetings [start, end]. Each meeting takes the lowest-numbered free room when it starts; if none is free, it waits. Return the room that hosted the most meetings (ties broken by lowest number).

Examples#

  • n = 2, meetings = [[0,10],[1,5],[2,7],[3,4]]0

Constraints#

  • 1 <= n <= 100, 1 <= meetings.length <= 10^5.

Hints#

Hint 1
Two heaps: free rooms (min-heap by room number) and busy rooms (min-heap by (end, room)).

Approach#

Sort meetings by start. Maintain two heaps: free (rooms currently available, by number) and busy (rooms in use, by end time then room number). For each meeting: free up expired rooms; if any free, use the lowest-numbered; else wait until the earliest busy room frees (delay this meeting’s end accordingly).

Solution#

Meeting Rooms III
class Solution {
public:
int mostBooked(int n, vector<vector<int>>& meetings) {
sort(meetings.begin(), meetings.end());
priority_queue<int, vector<int>, greater<int>> freeRooms;
for (int i = 0; i < n; ++i) freeRooms.push(i);
priority_queue<pair<long long,int>, vector<pair<long long,int>>, greater<>> busy;
vector<int> count(n, 0);
for (auto& m : meetings) {
long long s = m[0], e = m[1];
while (!busy.empty() && busy.top().first <= s) {
freeRooms.push(busy.top().second);
busy.pop();
}
if (!freeRooms.empty()) {
int r = freeRooms.top(); freeRooms.pop();
busy.push({e, r});
++count[r];
} else {
auto [end, r] = busy.top(); busy.pop();
busy.push({end + (e - s), r});
++count[r];
}
}
int best = 0;
for (int i = 1; i < n; ++i) if (count[i] > count[best]) best = i;
return best;
}
};

Editorial#

Two heaps decouple the two priority orders: rooms-by-number for selection, busy-rooms-by-end for the “wait for earliest free” branch. The (end, room) ordering on busy ensures ties between equal-end rooms go to the lower number — required by the problem.

Complexity#

  • Time: O(m log m + m log n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.