Algo-Sim › Intervals

Meeting Rooms

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

Can one person attend every meeting? Sort by start and check each meeting against the one before it.

Problem

Each meeting is an interval [start, end). Return true if one person could attend all of them, that is, no two meetings overlap. A meeting may start at the exact moment another one ends.

Constraints

Edge cases to test

Follow-up questions

How many rooms would you need?
Sort start and end times separately and sweep, or keep a min-heap of end times (LC 253): O(n log n).
What if you need the free slots common to many people?
Merge everyone’s busy intervals, then the gaps are the free times (LC 759).

Solution

Java

public boolean canAttendMeetings(int[][] intervals) {
    Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
    for (int i = 1; i < intervals.length; i++) {
        if (intervals[i][0] < intervals[i - 1][1]) {
            return false;
        }
    }
    return true;
}

Python

def can_attend_meetings(intervals):
    intervals.sort(key=lambda iv: iv[0])
    for i in range(1, len(intervals)):
        if intervals[i][0] < intervals[i - 1][1]:
            return False
    return True

C++

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

class Solution {
  public:
    bool canAttendMeetings(vector<vector<int>> &intervals) {
        sort(intervals.begin(), intervals.end(), [](const auto &a, const auto &b) { return a[0] < b[0]; });
        for (int i = 1; i < int(intervals.size()); i++) {
            if (intervals[i][0] < intervals[i - 1][1]) {
                return false;
            }
        }
        return true;
    }
};

More Intervals problems