Meeting Rooms Problem
Description
LeetCode Problem 252.
You are given an array of meeting times intervals where intervals[i] = [start_i, end_i].
A person can attend all meetings if no two meeting intervals overlap. Meetings ending at time t and starting at time t do not overlap.
Return true if a person can attend all meetings. Otherwise, return false.
Example 1:
Input: intervals = [[0,30],[5,10],[15,20]]
Output: false
Example 2:
Input: intervals = [[7,10],[2,4]]
Output: true
Constraints:
0 <= intervals.length <= 10^4intervals[i].length == 20 <= start_i < end_i <= 10^6
Solution
Approach: Sort by Start Time
If we sort the meetings by start time, a person can attend all of them exactly when each meeting ends no later than the next one starts. A meeting that overlaps another one later in the order also overlaps the one right after it, because that one starts even earlier, so checking neighbors is enough.
Sort, then compare intervals[i - 1][1] (the previous end) with intervals[i][0] (the current start). If the previous meeting ends after the current one starts, return false.
Use >, not >=: a meeting ending at time t and another starting at t do not overlap. An empty list or a single meeting has nothing to compare and is true.
Complexity: O(n log n) time for sorting and O(log n) extra space for the sort (O(n) in some languages).
class Solution:
def canAttendMeetings(self, intervals: List[List[int]]) -> bool:
intervals.sort() # by start time
for i in range(1, len(intervals)):
# The previous meeting must end before (or exactly when) this one starts.
if intervals[i - 1][1] > intervals[i][0]:
return False
return True