Skip to main content
67

Meeting Rooms II

Mediumintervalsheapsorting

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:IntervalsRead the beginner guide

Given an array of meeting time intervals, return the minimum number of meeting rooms needed so that every meeting has a room for its whole duration.

Understand the problem

  • Each interval [start, end] is a meeting from start up to end.
  • Two meetings that overlap in time need different rooms.
  • Meetings that only touch, like [1, 2] and [2, 3], do not overlap: a room freed at time t can host a meeting that starts at t.
  • The meetings are not given in time order.

Example 1

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

[0, 30] takes one room for the whole time. [5, 10] and then [15, 20] can share a second room.

Example 2

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

They don't overlap, so one room is enough.

Example 3

text
Input:  intervals = [[1, 5], [2, 6], [3, 7]]
Output: 3

At time 3, all three meetings are running.

Constraints

  • 0 <= intervals.length <= 10^4
  • 0 <= start < end <= 10^6

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    The number of rooms needed is the largest number of meetings happening at the same moment, so walk through time counting meetings as they start and end, and remember the highest count.

    The naive approach (and why it's slow)

    Check every moment in time and count the meetings running at that moment. Times go up to 10^6, and each check looks at every meeting: far too slow. Comparing every pair of meetings doesn't directly give the answer either.

    The key insight: count meetings running at once

    Each running meeting needs its own room, and a room becomes free when its meeting ends. So the answer is simply the busiest moment: the most meetings running at the same time.

    And the count only changes at a start (+1) or an end (−1). So you only need to look at those moments, in time order.

    Approach 1: two sorted lists (the JS/TS solution)

    1. Put all start times in one array and all end times in another. Sort both.
    2. Walk through the starts. Before counting a new start, release every meeting that has ended by then (end <= start): rooms-- for each.
    3. Then rooms++ for the new meeting, and remember the maximum.

    Ties go to the end (<=): a meeting ending at t frees its room for one starting at t.

    Splitting starts from ends "forgets" which end belongs to which meeting. That's fine: only the count at each moment matters.

    Step by step

    intervals = [[0, 30], [5, 10], [15, 20]]. Sorted: starts = [0, 5, 15], ends = [10, 20, 30].

    text
    time:  0    5    10   15   20        30
           [==================================]   [0, 30]
                [====]                            [5, 10]
                          [====]                  [15, 20]
    rooms: 1    2    1    2    1         0
    Next startEnds <= it (release)rooms after the startMost
    0none11
    5none (10 > 5)22
    1510 → rooms 2 − 1 = 122

    Answer: 2.

    Approach 2: a min-heap of end times (the Python solution)

    Sort the meetings by start. Keep a min-heap (see the Heap primer) holding the end time of each room in use; its top is the room that frees up first.

    For each meeting: if the earliest-ending room is free by its start (heap top <= start), reuse it (pop). Then push this meeting's end. The heap's size at the end is the number of rooms.

    Same example: push 30 → [30]; at 5, 30 isn't free, push 10 → [10, 30]; at 15, 10 is free, pop it and push 20 → [20, 30]. Size 2.

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    • Time: O(n log n) for the sorting (and heap operations).
    • Memory: O(n) for the arrays or the heap.

    Common mistakes

    • Using < instead of <= when releasing rooms. A meeting ending at 10 should free its room for one starting at 10.
    • Returning the final rooms count instead of the maximum seen.
    • Forgetting the empty input. With no meetings, the answer is 0.

    Going deeper

    • This "sweep line" idea (turn intervals into +1 / −1 events and walk through them in order) solves many problems: the most overlapping intervals, the busiest time of day, the maximum number of people in a building.
    • Meeting Rooms (the first one) is the special case "is the answer 1?".

    Reference solution

    js
    /**
     * @param {number[][]} intervals
     * @return {number}
     */
    export default function minMeetingRooms(intervals) {
      // Only the count of running meetings matters, so starts and ends can be sorted separately.
      const starts = intervals.map(([start]) => start).sort((a, b) => a - b)
      const ends = intervals.map(([, end]) => end).sort((a, b) => a - b)
      let rooms = 0 // meetings running right now
      let most = 0 // the busiest moment so far: the answer
      let e = 0 // next end time to process
      for (let s = 0; s < starts.length; s++) {
        // First free every room whose meeting has ended by this start (ties: end first).
        while (ends[e] <= starts[s]) {
          rooms--
          e++
        }
        rooms++ // this meeting takes a room
        most = Math.max(most, rooms)
      }
      return most
    }
    ts
    export default function minMeetingRooms(intervals: number[][]): number {
      // Only the count of running meetings matters, so starts and ends can be sorted separately.
      const starts = intervals.map(([start]) => start).sort((a, b) => a - b)
      const ends = intervals.map(([, end]) => end).sort((a, b) => a - b)
      let rooms = 0 // meetings running right now
      let most = 0 // the busiest moment so far: the answer
      let e = 0 // next end time to process
      for (let s = 0; s < starts.length; s++) {
        // First free every room whose meeting has ended by this start (ties: end first).
        while (ends[e] <= starts[s]) {
          rooms--
          e++
        }
        rooms++ // this meeting takes a room
        most = Math.max(most, rooms)
      }
      return most
    }
    python
    import heapq
    
    
    def min_meeting_rooms(intervals: list[list[int]]) -> int:
        # Min-heap of the end times of rooms in use: the top is the room that frees up first.
        ends_in_use = []
        for start, end in sorted(intervals):
            # The earliest-ending room is free by this start: reuse it.
            if ends_in_use and ends_in_use[0] <= start:
                heapq.heappop(ends_in_use)
            heapq.heappush(ends_in_use, end)  # this meeting holds a room until `end`
        return len(ends_in_use)  # rooms never shrink back, so this is the most ever needed