Meeting Rooms

Decide whether one person can go to every meeting on a list, with no two meetings at the same time.

Each meeting is written as a pair of times [start, end]. Given an array intervals of such pairs, return true if one person can attend all of the meetings, that is, if no two of them overlap, and false otherwise. A meeting that ends at some time t and another that starts at t do not overlap.

Example 1
Input: intervals = [[0,30],[5,10],[15,20]]
Output: false
Example 2
Input: intervals = [[7,10],[2,4]]
Output: true
Solution

The Idea

Picture a day in your calendar with several meetings booked. You can only sit in one of them at a time, so the day works only if each meeting is over before the next one begins. A stretch of time with a start and an end, such as [5, 10], is called an interval, which is where the array gets its name.

In Example 1 the meeting [0, 30] runs from time 0 to time 30. The meeting [5, 10] starts at 5, while [0, 30] is still going, so the person would have to be in two rooms at once. One clash is enough, and the answer is false.

Spotting that clash by eye was easy with three meetings. With many meetings in no particular order, though, which ones should we compare? Comparing every meeting with every other one works, but the number of comparisons grows quickly.

A calendar app does something simpler: it shows the meetings in the order they start. Look at the picture below, where each meeting is a bar on a time line, sorted by its start time.

Example 1 sorted by start: [0, 30], [5, 10] and [15, 20] on a time line from 0 to 30. [5, 10] starts at 5, before [0, 30] ends at 30, so they overlap. Example 2 sorted by start: [2, 4], then [7, 10], which starts at 7, after [2, 4] ends at 4, leaving a free gap.

In the top part, labelled "Example 1, sorted by start", the dashed orange line marks time 5. That is where [5, 10] begins, and the bar for [0, 30] above it has not ended yet. In the lower part, labelled "Example 2, sorted by start", [2, 4] ends at 4 and [7, 10] begins at 7. The two dashed green lines show the free gap between them.

Once the meetings are in start order, each one only has to be compared with the meeting right before it. If every meeting starts at or after the end of the one before it, the meetings follow each other like beads on a string, and no two of them can overlap anywhere.

Solution Approach

Turning that idea into code means settling four things: why comparing every pair is slow, how to put the meetings in start order, the exact test between two neighbouring meetings, and how to leave the caller's array as it was.

Comparing every pair

What would the plain way cost? Two loops, one inside the other, can compare each meeting with every later one. For n meetings that is n(n - 1)/2 comparisons: 3 for Example 1, but about 500,000 for 1,000 meetings. Sorting first brings the work down to the cost of the sort plus one pass.

Putting the meetings in start order

How does Java sort an array of pairs? Arrays.sort accepts a comparator, a small function that is handed two meetings and says which one comes first. Here it compares the start times, the value at index 0 of each pair:

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

Why is the meeting right before enough? Suppose every meeting starts at or after the end of the one before it. Each meeting also ends at or after its own start. So the end times only ever grow along the sorted list, and any later meeting starts after the current one has ended.

The test between two neighbours

When do two neighbours clash? The later meeting clashes if it starts strictly before the earlier one ends. Starting exactly at the end is fine, because the problem says that touching meetings do not overlap, so the test uses < and not <=.

Leaving the input unchanged

Does the method need to change the caller's array? Sorting in place would reorder it, which can surprise whoever passed it in. Sorting a copy made with intervals.clone() avoids that. The copy is shallow, so it shares the same pairs, but only the order of those pairs changes.

Java Solution

The method canAttendMeetings works in these steps:

  1. First, copy the array with intervals.clone() into sorted, so the caller's array keeps its order.
  2. Sort sorted by start time with Arrays.sort and the comparator (a, b) -> Integer.compare(a[0], b[0]).
  3. A loop moves i from 1 to the last position. For each i, it compares the start of meeting i, sorted[i][0], with the end of the meeting before it, sorted[i - 1][1]. If the start is smaller, the two clash and the method returns false.
  4. If the loop gets through every neighbour without a clash, the method returns true. With zero meetings or one meeting the loop never runs, so the answer is true as well.

The main method runs both examples, two meetings that touch, four touching meetings given out of order, an empty array and a single meeting, and then prints Example 1's array again.

Java
import java.util.Arrays;

public class MeetingRooms {

    public static boolean canAttendMeetings(int[][] intervals) {
        int[][] sorted = intervals.clone();
        Arrays.sort(sorted, (a, b) -> Integer.compare(a[0], b[0]));  // by start time
        for (int i = 1; i < sorted.length; i++) {
            if (sorted[i][0] < sorted[i - 1][1]) {
                return false;                  // starts before the previous one ends
            }
        }
        return true;
    }

    public static void main(String[] args) {
        int[][] example1 = {{0, 30}, {5, 10}, {15, 20}};
        System.out.println(canAttendMeetings(example1));
        System.out.println(canAttendMeetings(new int[][] {{7, 10}, {2, 4}}));
        System.out.println(canAttendMeetings(new int[][] {{1, 5}, {5, 8}}));
        System.out.println(canAttendMeetings(new int[][] {{9, 12}, {1, 3}, {3, 6}, {6, 9}}));
        System.out.println(canAttendMeetings(new int[][] {}));
        System.out.println(canAttendMeetings(new int[][] {{4, 6}}));
        System.out.println(Arrays.deepToString(example1));
    }
}

Running it prints:

Output
false
true
true
true
true
true
[[0, 30], [5, 10], [15, 20]]

The opening false is Example 1, where [5, 10] starts at 5, before [0, 30] ends. Example 2 gives true even though [7, 10] was listed first, because the sort puts [2, 4] ahead of it.

The third line, true, comes from [1, 5] and [5, 8], which touch at time 5. Here the < in the test matters. With <= instead, the same input returns false, as if one person could not leave one meeting and walk into the next.

The fourth line is also true: sorted, the meetings read [1, 3], [3, 6], [6, 9], [9, 12], each starting the moment the one before it ends. The empty array and the single meeting [4, 6] both print true, since there is no pair to clash. The last line shows Example 1's array in its original order, untouched by the sort.

Complexity

The work is the sort, plus one pass that compares each meeting with the one before it.

  • Time: O(n log n), because sorting the n meetings by start time costs O(n log n), and the pass that follows looks at each meeting once.
  • Space: O(n), because the copy made by clone() holds n references to the meetings, and Arrays.sort on an array of objects may use up to O(n) extra working memory too.

When the meetings may overlap and the question is how many rooms they need, see Meeting Rooms II.