Meeting Rooms II

Minimum rooms required for all meetings — sweep starts and ends with a heap (or sorted-arrays merge).

Medium
Time O(n log n) Space O(n)
LeetCode
4 min read
intervals heap

Problem#

Given an array of meeting time intervals, return the minimum number of conference rooms needed.

Examples#

  • [[0,30],[5,10],[15,20]]2
  • [[7,10],[2,4]]1

Constraints#

  • 1 <= intervals.length <= 10^4.

Hints#

Hint 1
After sorting by start, a min-heap of end-times tells you which room frees up first.

Approach#

Two sorted arrays — sort starts and ends separately; sweep both, incrementing rooms on start, decrementing on end.
Min-heap by end time — sort intervals by start; for each new meeting pop the top if its end ≤ new start (reuse the room), else push (new room needed).

Solution#

Meeting Rooms II (min-heap)
class Solution {
public:
int minMeetingRooms(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end());
priority_queue<int, vector<int>, greater<int>> pq;
for (auto& it : intervals) {
if (!pq.empty() && pq.top() <= it[0]) pq.pop();
pq.push(it[1]);
}
return pq.size();
}
};

Editorial#

The heap’s size is exactly the number of rooms currently in use. When a meeting starts, we check if any earlier-ending meeting has already finished — if so, we reuse its room (pop top, push our end). If not, we add a room. The heap’s max size during the sweep is the answer.

Complexity#

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

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.