The number of rooms is the peak number of meetings underway. Add \(1\) at each start and \(-1\) at each end; the prefix sum is the occupancy.
A difference array up to the latest end time, then one scan, yields that peak.
We can implement this using a difference array.
First, we find the maximum end time of all the meetings, denoted as \(m\). Then, we create a difference array \(d\) of length \(m + 1\). For each meeting, we add to the corresponding positions in the difference array: \(d[l] = d[l] + 1\) for the start time, and \(d[r] = d[r] - 1\) for the end time.
Next, we calculate the prefix sum of the difference array and find the maximum value of the prefix sum, which represents the minimum number of meeting rooms required.
The time complexity is \(O(n + m)\) and the space complexity is \(O(m)\), where \(n\) is the number of meetings and \(m\) is the maximum end time.
A large time horizon wastes an \(O(m)\) array. A hash map stores updates only at endpoints; sorting the keys and taking a prefix-sum peak is equivalent.
If the meeting times span a large range, we can use a hash map instead of a difference array.
First, we create a hash map \(d\), where we add to the corresponding positions for each meeting's start time and end time: \(d[l] = d[l] + 1\) for the start time, and \(d[r] = d[r] - 1\) for the end time.
Then, we sort the hash map by its keys, calculate the prefix sum of the hash map, and find the maximum value of the prefix sum, which represents the minimum number of meeting rooms required.
The time complexity is \(O(n \times \log n)\) and the space complexity is \(O(n)\), where \(n\) is the number of meetings.