Home
DSA Patterns
Intervals
Meeting Rooms
Problem Understanding
Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], determine if a person can attend all meetings.
Example 1:
- Input:
[[0,30],[5,10],[15,20]] - Output:
false - Why? Meeting
[0,30]overlaps with both[5,10]and[15,20].
Example 2:
- Input:
[[7,10],[2,4]] - Output:
true
Note: LeetCode 252, linked above, is a LeetCode Premium problem — opening it needs a Premium subscription. Everything needed to solve it is on this page.
Algorithm Strategy
We simply need to check if any two intervals overlap. If we sort them by start time, we only need to check adjacent meetings.
- Sort: Sort intervals by
starttime. - Scan: Iterate through the sorted list.
- Check: If
current.start < previous.end, then there is an overlap. Returnfalseimmediately. - Result: If loop finishes without conflict, return
true.
Interactive Visualization
Visualize checking for conflicts one by one.
Dry Run
Input: [[0,30], [5,10], [15,20]]
| Step | Comparison | Overlap? | Action |
|---|---|---|---|
| Init | Sort | - | [[0,30], [5,10], [15,20]] |
| 1 | [0,30] vs [5,10] |
Yes (5 < 30) |
Return false |
| Final | - | - | False |
Edge Cases & Common Mistakes
- Empty Input:
[]->true. - Single Meeting:
[[1,2]]->true. - Touching:
[[1,2], [2,3]]->true. (Meeting 2 starts exactly when 1 ends).
Solution
Simple sorting solution O(N log N).
Meeting Rooms Code
1var canAttendMeetings = function(intervals) {2 intervals.sort((a, b) => a[0] - b[0]);3 for (let i = 1; i < intervals.length; i++) {4 if (intervals[i][0] < intervals[i - 1][1]) {5 return false;6 }7 }8 return true;9};
