Meeting Rooms
You're given an array of meeting times where intervals[i] = [start_i, end_i] is a meeting that starts at start_i and ends at end_i. Return true if one person could attend every meeting, meaning no two meetings overlap, and false otherwise. A meeting that ends exactly when another begins, like [5,10] and [10,15], is not a conflict. The meetings are listed in no particular order, and an empty list returns true.
Examples
intervals = [[0,30],[5,10],[15,20]] returns false
[0,30] is still running when [5,10] starts, and again when [15,20] starts, so no one can attend all three.
intervals = [[7,10],[2,4]] returns true
In time order the meetings are [2,4] then [7,10]. The first ends at 4, before the second starts at 7.
intervals = [[1,5],[5,8]] returns true
The first meeting ends at 5, the same moment the second begins. Back-to-back meetings are fine.
Constraints
- 0 <= intervals.length <= 10^4
- intervals[i].length == 2
- 0 <= start_i < end_i <= 10^6
Hints
If the meetings were listed in time order, where would a clash have to show up?
Sort the intervals by start time. Then you only need to compare each meeting with the one just before it.
Sort by start. For each meeting after the first, if its start is less than the previous meeting's end, return false. If the loop finishes, return true.
Drill This: Your Approach First
Approach
Sort the meetings by start time. After sorting, any conflict must show up between neighbors: if a meeting overlaps some later one, it also overlaps the meeting right after it, since that one starts even earlier. So scan once and return false as soon as a meeting starts before the previous one ends. The sort dominates; the scan uses O(1) extra space.
Time
O(n log n)
Space
O(n)
Pitfall
Solutions
class Solution {
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;
}
}from typing import List
class Solution:
def canAttendMeetings(self, intervals: List[List[int]]) -> bool:
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