The Meeting Rooms II problem involves finding the minimum number of meeting rooms required to accommodate all meetings without overlap. Each meeting is represented as an interval with a start and end time.
public int minMeetingRooms(int[][] intervals) {
if (intervals == null || intervals.length == 0) return 0;
// Sort intervals by start time
Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
// Min-heap to track end times of meetings
PriorityQueue heap = new PriorityQueue<>();
// Add the first meeting
heap.add(intervals[0][1]);
for (int i = 1; i < intervals.length; i++) {
// If the room due to free up the earliest is free, remove it
if (intervals[i][0] >= heap.peek()) {
heap.poll();
}
// Add the current meeting's end time to the heap
heap.add(intervals[i][1]);
}
// The size of the heap is the number of meeting rooms required
return heap.size();
}
Input: intervals = [[0,30],[5,10],[15,20]]
Output: 2
Explanation: Two meeting rooms are required:
- Room 1: [0,30]
- Room 2: [5,10] and [15,20]
O(n log n)
- Sorting the intervals takes O(n log n)
.
- Each insertion and removal operation in the min-heap takes O(log k)
, where k
is the size of the heap. In the worst case, this is O(n log n)
.
O(n)
- The heap can grow to the size of all intervals in the worst case.