Meeting Rooms II (Min Rooms)

Find the fewest rooms that can hold a list of meetings, so that no two meetings in one room overlap.

Each meeting is written as a pair [start, end]. Given an array intervals of such meetings, return the smallest number of rooms that can hold all of them, where two meetings in the same room must not overlap. A meeting that ends at time t frees its room for a meeting that starts at t.

Example 1
Input: intervals = [[0,30],[5,10],[15,20]]
Output: 2
Explanation: [0,30] needs its own room. [5,10] and [15,20] can share a second room.
Example 2
Input: intervals = [[7,10],[2,4]]
Output: 1
Explanation: [2,4] is over before [7,10] starts, so one room holds both.
Solution

The Idea

Picture an office where meeting rooms are booked for the day. Example 1 has three bookings: one from 0 to 30, one from 5 to 10 and one from 15 to 20. The first meeting takes a room at time 0. At time 5 that room is still in use, so the second meeting needs a second room.

The real question comes at time 15, when the third meeting starts. Does it need a third room, or can it use one of the two already open? Look at the picture below.

Example 1 on a time line from 0 to 30. Room 1 holds [0, 30]. Room 2 holds [5, 10], is free from 10, and then holds [15, 20]. A dashed line at time 15 shows that room 1 is busy until 30 while room 2 is free.

The dashed line marks time 15. Room 1 is busy until 30, but room 2 has been free since its meeting [5, 10] ended at 10. So [15, 20] goes into room 2, and two rooms hold all three meetings.

At each start, then, only one room is worth checking: the one whose meeting ends first. If that room is free, the new meeting takes it. If even that room is still busy, every other room is busy too, and a new room has to be opened.

Checking only that one room works only if meetings are placed in the order they start, the way a real day unfolds. It also needs a quick way to find the earliest end time among the rooms in use.

Solution Approach

Turning that idea into code means settling three things: the order to place meetings in, how to find the room that frees up first, and what number to return. There is also another way, which counts with two sorted arrays instead of a heap.

Placing meetings by start time

Which meeting should be placed first? The one that starts first. The input does not have to be in that order: Example 2 lists [7, 10] before [2, 4]. So the code sorts a copy of the array by start time, which leaves the caller's array as it was. The sort needs a rule for comparing two meetings, called a comparator:

Java
Comparator<int[]> byStart = (a, b) -> Integer.compare(a[0], b[0]);

It compares the first numbers of two pairs, so meetings come out in order of start time. The solution passes the same rule straight to Arrays.sort.

Finding the room that frees up first

How do we find the earliest end time quickly? A plain list with one end time per room works, but each new meeting would scan the whole list. Say there are n meetings and all of them overlap: the list grows to n entries, and the scans add up to about n²/2 steps.

A min-heap does better. It is a collection that always keeps its smallest value on top, so the earliest end time would always be ready to read. Reading the top is immediate, and removing the top or adding an end time takes about log n steps when it holds n of them. In Java, a PriorityQueue of end times can do this job. Created without a comparator, it orders Integer values smallest first, so it is a min-heap:

Java
PriorityQueue<Integer> endTimes = new PriorityQueue<>();

In Example 1, after the first two meetings, endTimes holds 10 and 30, one end time per room, with 10 on top. When [15, 20] starts, the top, 10, is at most 15, so that room is free. The code removes 10 with poll and adds 20, the new meeting's end. The test is "at most" rather than "less than" because a room freed at 10 can take a meeting that starts at 10.

The number to return

What does endTimes hold at the end? Still one end time per room. Each meeting either takes over a freed room, replacing that room's end time, or opens a new room and adds one. So the heap grows only when every room is busy, and its final size is the number of rooms opened. Example 1 ends with 20 and 30 in the heap: two rooms.

Optional: two sorted arrays instead of a heap

Another way counts how many meetings run at once. Put all start times into one sorted array and all end times into another. For Example 1 these are 0, 5, 15 and 10, 20, 30. Walk through the start times, and before each start, step past every end time that is at or before it.

At 0 and at 5 no meeting has ended, so 1 and then 2 rooms are in use. At 15, the end time 10 is stepped past: three meetings have started and one has ended, so again 2. The largest count seen, 2, is the answer, and the two sorts make this way O(n log n) time.

Java Solution

The method minMeetingRooms works in these steps:

  1. First, copy the input with intervals.clone() into sorted, and sort that copy by start time with Arrays.sort and the comparator.
  2. Create endTimes, a PriorityQueue<Integer> min-heap that will hold one end time for each room in use.
  3. Go through sorted with a loop that calls each pair meeting. If the heap is not empty and its top, endTimes.peek(), is at most the start meeting[0], that room is free, so remove its end time with poll.
  4. Either way, add the meeting's end, meeting[1], to the heap: the meeting now holds a room until then.
  5. After the loop, return endTimes.size(), the number of rooms opened.

The main method runs both examples, two meetings that touch at 5, three identical meetings, Example 1 in a shuffled order, one long meeting with three short ones inside it, and no meetings at all. A small helper, run, prints each input with its answer.

Java
import java.util.Arrays;
import java.util.PriorityQueue;

public class MeetingRoomsII {

    public static int minMeetingRooms(int[][] intervals) {
        int[][] sorted = intervals.clone();
        Arrays.sort(sorted, (a, b) -> Integer.compare(a[0], b[0])); // by start time

        PriorityQueue<Integer> endTimes = new PriorityQueue<>(); // smallest end time on top
        for (int[] meeting : sorted) {
            if (!endTimes.isEmpty() && endTimes.peek() <= meeting[0]) {
                endTimes.poll();              // that room is free again: reuse it
            }
            endTimes.add(meeting[1]);         // this meeting holds a room until its end
        }
        return endTimes.size();
    }

    static void run(int[][] intervals) {
        String input = Arrays.deepToString(intervals);
        System.out.println(input + " -> " + minMeetingRooms(intervals));
    }

    public static void main(String[] args) {
        run(new int[][] {{0, 30}, {5, 10}, {15, 20}});
        run(new int[][] {{7, 10}, {2, 4}});
        run(new int[][] {{1, 5}, {5, 8}});
        run(new int[][] {{1, 4}, {1, 4}, {1, 4}});
        run(new int[][] {{15, 20}, {0, 30}, {5, 10}});
        run(new int[][] {{1, 10}, {2, 3}, {4, 5}, {6, 7}});
        run(new int[][] {});
    }
}

Running it prints:

Output
[[0, 30], [5, 10], [15, 20]] -> 2
[[7, 10], [2, 4]] -> 1
[[1, 5], [5, 8]] -> 1
[[1, 4], [1, 4], [1, 4]] -> 3
[[15, 20], [0, 30], [5, 10]] -> 2
[[1, 10], [2, 3], [4, 5], [6, 7]] -> 2
[] -> 0

Look at the third line: [1, 5] and [5, 8] share one room, because the check is <= and the first meeting ends exactly when the second starts. The three copies of [1, 4] on the fourth line all run at once, so they need 3 rooms.

The fifth line is Example 1 in the order [15, 20], [0, 30], [5, 10], and it still gives 2 thanks to the sort. A test copy of the loop without the sort prints 3 for this input. There, [15, 20] opens a room with end time 20 and [0, 30] opens a second. At [5, 10] the earliest end is 20, so a third room opens, although at time 5 the meeting [15, 20] has not even started.

On the sixth line, [1, 10] keeps one room while [2, 3], [4, 5] and [6, 7] take turns in a second, so the answer is 2. The last line gives 0, because with no meetings the heap stays empty.

Complexity

The work is one sort, then at most two heap steps for each meeting.

  • Time: O(n log n), because sorting the n meetings takes O(n log n), and each meeting does at most one poll and one add on a heap of at most n end times, about log n steps each.
  • Space: O(n), because the sorted copy holds all n meetings, and the heap holds n end times when every meeting overlaps all the others, as the three copies of [1, 4] do.

Checking whether one room is enough for all the meetings is Meeting Rooms.