LeetCode Solutions

253. Meeting Rooms II

Time: $O(n\log n)$

Space: $O(n)$

			

class Solution {
 public:
  int minMeetingRooms(vector<vector<int>>& intervals) {
    // Store end times of each room
    priority_queue<int, vector<int>, greater<>> minHeap;

    sort(begin(intervals), end(intervals));

    for (const vector<int>& interval : intervals) {
      if (!minHeap.empty() && interval[0] >= minHeap.top())
        minHeap.pop();  // No overlap, we can reuse the same room
      minHeap.push(interval[1]);
    }

    return minHeap.size();
  }
};
			

class Solution {
  public int minMeetingRooms(int[][] intervals) {
    // Store end times of each room
    Queue<Integer> minHeap = new PriorityQueue<>((a, b) -> a - b);

    Arrays.sort(intervals, (a, b) -> (a[0] - b[0]));

    for (int[] interval : intervals) {
      if (!minHeap.isEmpty() && interval[0] >= minHeap.peek())
        minHeap.poll(); // No overlap, we can reuse the same room
      minHeap.offer(interval[1]);
    }

    return minHeap.size();
  }
}
			

class Solution:
  def minMeetingRooms(self, intervals: List[List[int]]) -> int:
    minHeap = []  # Store end times of each room

    for start, end in sorted(intervals):
      if minHeap and start >= minHeap[0]:
        heapq.heappop(minHeap)
      heapq.heappush(minHeap, end)

    return len(minHeap)