Meeting Rooms II
Master this topic with zero to advance depth.
Meeting Rooms II
Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], return the minimum number of conference rooms required.
Visual Representation
intervals = [[0,30],[5,10],[15,20]]
Timeline:
0 5 10 15 20 30
|--|---|---|----|----|
[0 30] (Room 1)
[5 10] (Room 2)
[15 20] (Room 2 - reused)
Max overlapping at any time: 2Examples
Level I: Min-Heap (Interval Management)
Intuition
Sort the meetings by start time. Use a Min-Heap to track the end times of meetings currently in progress. If a new meeting starts after the earliest meeting ends (root of the heap), we can reuse that room.
Thought Process
- Sort
intervalsby start time. - Initialize a Min-Heap to store end times.
- For each interval:
- If heap is not empty and
heap.peek() <= current.start, pop the heap (room becomes free). - Push current interval's end time to heap.
- If heap is not empty and
- The final size of the heap is the number of rooms needed.
Detailed Dry Run
intervals = [[0,30],[5,10],[15,20]]
- Sorted: [[0,30],[5,10],[15,20]]
- Int [0,30]: Heap [30]
- Int [5,10]: Heap.peek(30) > 5. Push 10. Heap [10, 30]
- Int [15,20]: Heap.peek(10) <= 15. Pop 10. Push 20. Heap [20, 30] Result: Heap size = 2
Level II: Sweep Line (Difference Array Logic)
Intuition
Record all 'start' and 'end' events. A 'start' event increases the room count by 1, and an 'end' event decreases it by 1. The maximum room count at any point is our answer.
Thought Process
- For each interval , create two points: and .
- Sort todos points by time.
- If times are equal, process end events before start events if the interval is exclusive, OR start before end if inclusive. (LeetCode meetings are inclusive of start, exclusive of end, so end before start at same time).
- Traverse through sorted points and maintain a running sum.
Detailed Dry Run
intervals = [[0,30],[5,10],[15,20]]
- Events: (0,+1), (30,-1), (5,+1), (10,-1), (15,+1), (20,-1)
- Sorted: (0,+1), (5,+1), (10,-1), (15,+1), (20,-1), (30,-1)
- Sums: 1 -> 2 -> 1 -> 2 -> 1 -> 0 Max Sum: 2
Level III: Two Pointers (Chronological Ordering)
Intuition
Separate start times and end times and sort both. Iterate through the start times. If a start time is before the earliest end time, we need a room. If not, a room just became free, so we can move the end-time pointer.
Logic Steps
- Extract all
startsandendsinto separate arrays. - Sort both arrays.
- Use two pointers
sande. - If
starts[s] < ends[e], incrementusedRoomsands. - Else (room freed), increment
eands(total rooms stays same).
Detailed Dry Run
starts = [0, 5, 15], ends = [10, 20, 30]
- s=0, e=0: starts[0]=0 < ends[0]=10 -> rooms=1, s=1
- s=1, e=0: starts[1]=5 < ends[0]=10 -> rooms=2, s=2
- s=2, e=0: starts[2]=15 >= ends[0]=10 -> rooms=2, e=1, s=3 Result: 2 rooms.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.