Blind 75 · Intervals

Meeting Rooms II

Medium

Watch the walkthrough (6:08)

Problem

Given a list of meeting time intervals, return the minimum number of rooms needed to hold them all.
A room frees up the minute its meeting ends, so a meeting starting exactly then can reuse it.

Examples

Example 1:
Input: intervals = [[0,30],[5,10],[15,20]]
Output: 2

Example 2:
Input: intervals = [[7,10],[2,4]]
Output: 1

Example 3:
Input: intervals = [[1,5],[5,8],[8,12]]
Output: 1
Explanation: one room, reused twice at the boundary.

Example 4:
Input: intervals = [[1,10],[2,7],[3,19],[8,12],[10,20],[11,30]]
Output: 4

Constraints

1 <= intervals.length <= 10^4
intervals[i] is [start, end] with 0 <= start < end <= 10^6

Prerequisites

Sorting as a setup move — most interval problems are one sort away from a single sweep, and choosing whether to sort by START or by END is the decision that matters.

How to think about it

1. Sort by Start, Reuse the Earliest Room Optimal

Intuition

Sorted by start, each meeting only has to ask whether some room is already done when it starts, and the room to ask is the one that ends earliest: if even that room is not done, no room is. So keep every room's end in a min-heap, the earliest on top. For each meeting, if the earliest end is at or before its start, that room is done and is reused: pop its end. Either way, push the meeting's end. The heap holds one end per room, so its size is the answer. A room is done when its meeting ends at or before the new start, so the check is less than or equal: a meeting may start exactly when another ends and take its room. If the check were strictly less than, the walkthrough's 5..8, which starts where 3..5 ends, would open a fourth room, and the answer would be 4 instead of 3. Sort by start; reuse the earliest-ending room if it's done, or add a room.

Algorithm

1. Sort the meetings by start.
2. For each meeting, if the earliest end in the heap is at or before its start, pop it: that room is reused.
3. Push the meeting's end.
4. Return the heap's size.

Time & Space

Time O(n log n) for the sort and a heap step per meeting. Space O(n) for the heap.

2. Peak Concurrency by Sweep Optimal

Intuition

Rooms needed equals the largest number of meetings running at the same moment. Detach starts from ends, sort each, and sweep: a start before the next end takes a room, an end at or before the next start frees one. Ends win ties, which is exactly the rule that lets a room be reused the minute it frees.

Algorithm

1. Collect and sort all start times and all end times separately.
2. Walk the starts; before each, release every room whose end is at or before it.
3. Take a room, and track the peak.

Time & Space

Time O(n log n). Space O(n). A min-heap of end times expresses the same sweep.