InterviewPrepKit

Home / Coding / Intervals

Meeting Rooms II

medium Original β†—
Solving tips
  • The answer is peak concurrency (max simultaneous meetings), and that peak only occurs at a meeting's start time.
  • Sort by start and keep a min-heap of end times: if the earliest end <= new start reuse that room (heapreplace), else push a new one; the heap size is the answer.
  • Alternative with no heap: sort all starts and all ends separately and two-pointer sweep, doing +1 per start and processing frees (end <= start) before each increment.
  • Boundary: a room ending at t is free for a meeting starting at t, so use '<=' in the free-room test; both approaches are O(n log n) time, O(n) space.

Problem

You are given a list of meetings as half-open time ranges [start, end). Every meeting must be held in some conference room, and a room can host only one meeting at a time. A room frees up the instant its meeting ends, so a meeting starting at time t can reuse a room whose previous meeting ended at t. Return the minimum number of conference rooms needed to schedule all the meetings.

Equivalently: what is the maximum number of meetings that are ever in progress at the same moment?

Examples

  • intervals = [[0,30],[5,10],[15,20]] β†’ 2 β€” [0,30] occupies one room the whole time; [5,10] and [15,20] don’t overlap each other, so they share a second room.
  • intervals = [[7,10],[2,4]] β†’ 1 β€” the meetings never coexist.
  • intervals = [[1,4],[2,5],[3,6]] β†’ 3 β€” at time 3 all three are running at once.

Constraints

  • 1 <= len(intervals) <= 10^4
  • 0 <= start < end <= 10^6

10^4 meetings makes O(n^2) counting borderline; the expected solutions are O(n log n).

Think about it first

Hint 1 The answer is the peak number of simultaneously running meetings. When can that peak occur β€” at arbitrary times, or only at moments when some meeting starts?
Hint 2 Process meetings sorted by start. For each new meeting, you need to know one thing: has any currently running meeting already finished? Which running meeting should you check first, and what data structure serves that up cheaply?
Hint 3 Two classic routes: (a) keep a min-heap of end times β€” pop the earliest end if it's ≀ the new start, then push the new end; the heap's peak size is the answer. (b) Sort all starts and all ends separately and advance two pointers, +1 room per start not matched by an earlier end.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.