Meeting Rooms II Problem
Description
LeetCode Problem 253.
Given an array of meeting time intervals intervals where intervals[i] = [start_i, end_i], return the minimum number of conference rooms required.
Example 1:
Input: intervals = [[0,30],[5,10],[15,20]]
Output: 2
Example 2:
Input: intervals = [[7,10],[2,4]]
Output: 1
Constraints:
1 <= intervals.length <= 10^40 <= start_i < end_i <= 10^6
Solution
Approach: Sorted Start and End Times
The number of rooms we need is the largest number of meetings going on at the same time. To count that, we only need the start times and the end times; which start belongs to which end does not matter.
Sort the starts and the ends separately. Go through the starts in order, with a pointer j into the ends (the meetings before j have already finished):
- If
ends[j] <= start, some meeting has ended by the time this one starts. The new meeting can take its room, so movejforward and do not add a room. - Otherwise every room in use is still busy, so we need one more room.
The comparison is <= because a room freed at time t can host a meeting that starts at t. For example [[1,5],[5,10]] needs one room, not two.
Complexity: O(n log n) time for sorting and O(n) extra space for the two arrays.
class Solution:
def minMeetingRooms(self, intervals: List[List[int]]) -> int:
starts = sorted(s for s, _ in intervals)
ends = sorted(e for _, e in intervals)
rooms = 0
j = 0 # ends[:j] are the meetings that have already finished
for s in starts:
if ends[j] <= s:
j += 1 # a meeting ended by now: reuse its room
else:
rooms += 1 # every room is busy: open a new one
return rooms