An interactive visualization of the min-heap approach to Meeting Rooms II. Watch how sorting by start time and tracking end times with a heap determines the minimum number of conference rooms needed.
Intervals LeetCode 253 ↗ Mediumintervals where
intervals[i] = [start_i, end_i], return the minimum number of
conference rooms required.import java.util.PriorityQueuefun minMeetingRooms(intervals: Array<IntArray>): Int { if (intervals.isEmpty()) return 0 intervals.sortBy { it[0] } val heap = PriorityQueue<Int>() // min-heap of end times for (interval in intervals) { val start = interval[0] val end = interval[1] if (heap.isNotEmpty() && heap.peek() <= start) { heap.poll() // reuse room } heap.add(end) } return heap.size}
If we process meetings in order of start time, the only question at each step is: can we reuse a room that has already freed up? A room is free when its meeting has ended. The meeting that frees up earliest is the one with the smallest end time — exactly what a min-heap gives us in O(log n).
[start, end]:
Each element in the heap represents a room currently in use. When a meeting ends before the next one starts, we can recycle that room (pop + push keeps heap size the same). When there is a conflict, we must allocate a new room (push without pop increases heap size). The maximum heap size over the entire process is the answer — and since we only add rooms when strictly necessary, that maximum is minimal.
Sorting takes O(n log n). Each of the n meetings involves at most one heap push and one heap pop, each O(log n). The heap stores at most n end times, so space is O(n).