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] = [start_i, end_i], return the minimum number of conference rooms required.
Visual Representation
Intervals: [[0, 30], [5, 10], [15, 20]]
Room 1: [0--------------------------30]
Room 2: [5---10] [15---20]
Max overlapping at any time: 2
Result: 2Examples
We need two rooms; one for [0, 30] and another for [5, 10] and [15, 20] sequentially.
Level I: Brute Force (Iterate All Time Points)
Intuition
Count the number of overlapping meetings at every possible time point. The maximum count across all time points is the minimum number of rooms needed.
Thought Process
- Find the
minStartandmaxEndacross all intervals. - For every time from
minStarttomaxEnd:- Count how many meetings are active at time (i.e.,
start <= t < end).
- Count how many meetings are active at time (i.e.,
- Return the maximum count found.
Detailed Dry Run
[[0, 30], [5, 10], [15, 20]]
- t=0: active=[[0,30]]. Count=1.
- t=5: active=[[0,30], [5,10]]. Count=2.
- t=15: active=[[0,30], [15,20]]. Count=2. Max count = 2.
Level II: Chronological Sorting (Sweep Line)
Intuition
When a meeting starts, we need a room; when it ends, we free a room. If we process all start and end points in chronological order, the max number of overlapping meetings at any point is our answer.
Thought Process
- Separate starts and ends into two sorted arrays.
- Use two pointers to iterate through them.
- If
startTime < endTime, a new meeting starts before an old one ends: incrementroomsandstartPtr. - Else, a meeting ends: decrement
roomsandendPtr.
Pattern: Sweep Line / Two Pointers
Detailed Dry Run
Starts: [0, 5, 15], Ends: [10, 20, 30]
- t=0: Start [0,30]. rooms=1. max=1.
- t=5: Start [5,10]. rooms=2. max=2.
- t=10: End [5,10]. rooms=1.
- t=15: Start [15,20]. rooms=2. max=2.
Level III: Optimal Greedy (Min-Heap)
Intuition
As we process meetings by start time, we use a Min-Heap to track the end times of rooms currently in use. The top of the heap is the room that will be free soonest.
Thought Process
- Sort meetings by start time.
- Add the first meeting's end time to a Min-Heap.
- For each next meeting, if its
start >= heap.peek()(earliest end), we can reuse that room:heap.pop(). - Always push current meeting's end time to the heap.
- Answer is
heap.size().
Pattern: Resource Allocation / Priority Queue
Detailed Dry Run
[[0,30],[5,10],[15,20]] Sorted
- [0,30]: Heap=[30], rooms=1
- [5,10]: 5 < 30? YES. Heap=[10, 30], rooms=2
- [15,20]: 15 >= 10? YES. Pop 10, Push 20. Heap=[20, 30], rooms=2
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.