Algo-Sim › Intervals

Meeting Rooms II

Medium · Intervals · step through it in Java, Python and C++ on your own input

Given meeting times, find the minimum number of rooms so no two meetings in one room overlap. A meeting may start when another ends.

Problem

Each meeting is an interval [start, end). Return the smallest number of rooms needed to hold every meeting, where a room can host one meeting at a time and a meeting may begin in a room at the exact moment another one ends there.

Constraints

Edge cases to test

Follow-up questions

Is there a way without a heap?
Sort starts and ends separately and sweep with two pointers, counting how many are open: O(n log n), simpler constants.
What if you must also say which room each meeting gets?
A min-heap of (end, room) plus a min-heap of free room numbers (LC 2402).

Solution

Java

public int minMeetingRooms(int[][] intervals) {
    int n = intervals.length;
    int[] starts = new int[n], ends = new int[n];
    for (int i = 0; i < n; i++) {
        starts[i] = intervals[i][0];
        ends[i] = intervals[i][1];
    }
    Arrays.sort(starts);
    Arrays.sort(ends);
    int rooms = 0, e = 0;
    for (int s = 0; s < n; s++) {
        if (starts[s] < ends[e]) {
            rooms++;
        } else {
            e++;
        }
    }
    return rooms;
}

Python

def min_meeting_rooms(intervals):
    starts = [iv[0] for iv in intervals]
    ends = [iv[1] for iv in intervals]
    starts.sort()
    ends.sort()
    rooms = e = 0
    for s in range(len(intervals)):
        if starts[s] < ends[e]:
            rooms += 1
        else:
            e += 1
    return rooms

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int minMeetingRooms(vector<vector<int>> &intervals) {
        int n = int(intervals.size());
        vector<int> starts = vector<int>(n), ends = vector<int>(n);
        for (int i = 0; i < n; i++) {
            starts[i] = intervals[i][0];
            ends[i] = intervals[i][1];
        }
        sort(starts.begin(), starts.end());
        sort(ends.begin(), ends.end());
        int rooms = 0, e = 0;
        for (int s = 0; s < n; s++) {
            if (starts[s] < ends[e]) {
                rooms++;
            } else {
                e++;
            }
        }
        return rooms;
    }
};

More Intervals problems