Problem solution · C++

Meeting Rooms III

Meeting Rooms III: a C++ solution using heap or priority queue. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Heap or priority queue
Source
walkccc LeetCode Solutions
Length
46 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Heap or priority queue

For Meeting Rooms III, the implementation repeatedly takes the currently best candidate from a heap while inserting newly available choices.

  1. Define the priority key and whether the smallest or largest item should lead.
  2. Push each candidate when it becomes eligible.
  3. Discard stale entries when necessary and process the best live candidate.

Code notes

  • 46 lines of C++ from the credited upstream file 2402.cpp.
  • The implementation visibly relies on sequence storage, work queue.
  • 3 loop blocks detected.

Complexity

Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeMeeting Rooms III · C++C++
Use this to learn the idea, then write your own version.
struct T {  long endTime;  int roomId;}; class Solution { public:  int mostBooked(int n, vector<vector<int>>& meetings) {    vector<int> count(n);     ranges::sort(meetings);     auto compare = [](const T& a, const T& b) {      return a.endTime == b.endTime ? a.roomId > b.roomId                                    : a.endTime > b.endTime;    };    priority_queue<T, vector<T>, decltype(compare)> occupied(compare);    priority_queue<int, vector<int>, greater<>> availableRoomIds;     for (int i = 0; i < n; ++i)      availableRoomIds.push(i);     for (const vector<int>& meeting : meetings) {      const int start = meeting[0];      const int end = meeting[1];      // Push meetings ending before this `meeting` in occupied to the      // `availableRoomsIds`.      while (!occupied.empty() && occupied.top().endTime <= start)        availableRoomIds.push(occupied.top().roomId), occupied.pop();      if (availableRoomIds.empty()) {        const auto [newStart, roomId] = occupied.top();        occupied.pop();        ++count[roomId];        occupied.push({newStart + (end - start), roomId});      } else {        const int roomId = availableRoomIds.top();        availableRoomIds.pop();        ++count[roomId];        occupied.push({end, roomId});      }    }     return ranges::max_element(count) - count.begin();  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗