← DSA
MEDIUM

Meeting Rooms II

PracticeNeetCode ↗LeetCode ↗

Given an array of meeting time intervals, find the minimum number of conference rooms required to hold all of them.

Example

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

Key Pointers

Step-by-Step Analysis

  1. Extract all start times into one sorted list and all end times into another.
  2. Walk both lists with two pointers, tracking rooms (currently in use) and max_rooms (the answer so far).
  3. If the current start is before the current earliest end, a new room is needed — increment rooms and advance the start pointer.
  4. Otherwise, a room just freed up — decrement rooms and advance the end pointer.
  5. Update max_rooms after every step and return it once the starts are exhausted.

Complexity

Time: O(n log n) for the sorts — Space: O(n)

Code

def minMeetingRooms(intervals: list[list[int]]) -> int:
    starts = sorted(i[0] for i in intervals)
    ends = sorted(i[1] for i in intervals)

    s = e = 0
    rooms = max_rooms = 0

    while s < len(starts):
        if starts[s] < ends[e]:
            rooms += 1
            s += 1
        else:
            rooms -= 1
            e += 1
        max_rooms = max(max_rooms, rooms)

    return max_rooms

Code Explanation

How the solution above works, piece by piece.

  1. Only the count of rooms matters, not which meeting uses which, so start and end times can be sorted separately.
  2. Walk both lists with two pointers, always taking the earlier event.
  3. A start before the next end means a new meeting begins while others are running: rooms += 1.
  4. Otherwise the earliest meeting has ended: a room frees up (rooms -= 1).
  5. The peak of rooms is the answer. O(n log n).

Visual Walkthrough

Running it on intervals = [[0, 30], [5, 10], [15, 20]]:

Two rooms are enough for the three meetingsroom 10 – 30room 25–1015–200102030t=0: start → 1 in uset=5: start → 2 in uset=10: end → 1 in uset=15: start → 2 in usemax at once = 2
Sorted start times and sorted end times are walked like a merge. A start before the next end needs an extra room; otherwise a meeting has ended and its room is free. The most rooms in use at once is 2.
room 1room 2 (reused)

Video Explanation

NeetCode — LeetCode 253