CodingNodes / Intervals / Meeting Rooms II System design Space play · ←→ step · R restart

Problem

Each meeting is a pair [start, end], and intervals lists all of them in any order. A room can host only one meeting at a time, but a meeting that starts exactly when another ends may use the same room.

Return the smallest number of rooms that lets every meeting take place.

Constraints

  • 1 ≤ intervals.length ≤ 10⁴
  • intervals[i].length == 2
  • 0 ≤ start < end ≤ 10⁶

Examples: pick one to animate

Solutions

TimeO(n log n) SpaceO(n)

Time: Sorting costs O(n log n), and each meeting does at most one pop and one push on a heap of size up to n, each O(log n).

Space: The heap holds one end time per busy room, up to n when every meeting overlaps.

Process meetings in order of start time and keep a min-heap of the end times of the rooms in use. The top of the heap is the room that frees up first. If it frees up by the time the new meeting starts, reuse that room (pop it); then push the new meeting's end. The heap size is the number of rooms in use.