LeetCode 253 Greedy + Min-Heap Medium

Meeting Rooms II β€” Greedy + Heap

Sort by start. A min-heap of room end-times tells you if the earliest-freeing room is open yet β€” O(N log N) time

The min-heap of end times

Given meeting intervals, how few rooms cover them all? The greedy plan: process meetings in order of start time. Keep a min-heap of the end times of rooms currently in use, so the room that frees up soonest is always on top.

For each meeting, peek the heap. If its earliest end time is ≤ this meeting's start, that room is free: reuse it (pop, push the new end). Otherwise every room is busy: open a new one (push). The answer is the largest the heap ever grows.

// sort meetings by start
for [s, e] in meetings:
  if heap && heap.top() <= s:
    heap.pop() # reuse a room
  heap.push(e)
answer = max(answer, heap.size())
LC
Meeting Rooms II (253): the canonical interval-scheduling problem. The min-heap of end times is the clean, general solution.
Open Problem
Time Complexity
O(N log N)

Sorting dominates; each meeting does O(log N) heap work.

Space Complexity
O(N)

Worst case every meeting overlaps and the heap holds all N end times.

Live Visualization
format: [start,end] [start,end] …
Current meeting Reused a room Opened new room Room end-time in heap
Meetings on a timeline (sorted by start)
Rooms in use min-heap of end times
meeting = – earliest free = – rooms now = 0 max rooms = 0
Step 0 / 0
Current meeting
–
[start, end]
Earliest free
–
heap top (end)
Rooms in use
0
heap size
Max needed
0
the answer
Enter meetings and hit Play to watch rooms open and get reused.
βœ“ Done Speed

Step-by-step trace

#ActionMeetingHeap topHeap (end times)RoomsMax
C++ β€” Meeting Rooms II (LC 253)
int minMeetingRooms(vector<vector<int>>& meetings) {
    if (meetings.empty()) return 0;

    // 1) sort by start time
    sort(meetings.begin(), meetings.end());

    // 2) min-heap of end times of rooms in use
    priority_queue<int, vector<int>, greater<>> pq;

    for (auto& m : meetings) {
        int s = m[0], e = m[1];
        // earliest-freeing room is done β‡’ reuse it
        if (!pq.empty() && pq.top() <= s) pq.pop();
        pq.push(e);            // occupy a room until e
    }
    return pq.size();   // rooms still needed = peak overlap
}

πŸ“ My Notes ●

β–Ύ