Meeting Rooms
Difficulty: Easy · Pattern: Intervals · LeetCode #252
Given meeting time intervals[i] = [start, end], determine whether one person could attend all of them. A meeting ending at time t and another starting at t do not conflict.
Examples
text
[[0,30],[5,10],[15,20]] → false
[[7,10],[2,4]] → trueHints
- After sorting by start time, only adjacent meetings can be the first conflict.
Approach
Sort by start, then check intervals[i].start < intervals[i−1].end for every i. If any pair overlaps, return false. O(n log n).
Why only adjacent pairs? If meeting i overlaps some earlier meeting j < i−1, then meeting i−1 starts between j's start and i's start, and either overlaps i or ends before i. In either case we'd find a conflict at an adjacent pair, or j already overlapped j+1.
Complexity
Time: O(n log n). Space: O(n) for the sorted copy.
Python solution
def canAttendMeetings(intervals):
intervals = sorted(intervals)
return all(intervals[i][0] >= intervals[i - 1][1] for i in range(1, len(intervals)))JavaScript solution
function canAttendMeetings(intervals) {
const a = [...intervals].sort((x, y) => x[0] - y[0]);
for (let i = 1; i < a.length; i++) if (a[i][0] < a[i - 1][1]) return false;
return true;
}