Minimum meeting rooms.
MediumGiven an array of meeting times intervals, where intervals[i] = [start, end], return the minimum number of conference rooms needed so that every meeting can take place. A meeting that ends at time t frees its room for a meeting that starts at time t.
Example 1
Input: intervals = [[0, 30], [5, 10], [15, 20]] Output: 2
The meeting from 0 to 30 needs its own room. The other two can share a second room.
Example 2
Input: intervals = [[7, 10], [2, 4]] Output: 1
Constraints
1 <= intervals.length <= 10^4intervals[i].length == 20 <= start < end <= 10^6
Approach
The number of rooms you need is the largest number of meetings in progress at the same time. That count only changes at start and end times, so sort the start times and the end times separately and sweep through them. Each start needs a room. If the earliest end time you haven't used yet is at or before that start, that meeting has finished and its room is free, so move past that end time and reuse the room. Otherwise, every room is busy and you open a new one.
Sorting the starts and ends separately breaks the link between each meeting's start and end, but that's fine. Only the number of meetings that have started and ended by each moment matters, not which meeting is which.
Steps
- Sort the start times and the end times into two separate lists.
- Set
rooms = 0and pointjat the first end time. - For each start time, if it's at or after
ends[j], movejforward to reuse that room. Otherwise, add one torooms. - Return
rooms.
Complexity
- Time:
O(n log n), for the two sorts. - Space:
O(n), for the two lists.
Common mistakes
- Opening a new room when a meeting starts at the exact moment another ends. Use
>=so the freed room is reused. - Sorting meetings by start time and comparing each one only with the previous meeting. A room can free up from any earlier meeting, not just the most recent one.
Interview experiences
1 sharedRelated courses


