Meeting Rooms
Easy · Intervals · Explanation and code example
Sorting
How it works
We want to determine whether a person can attend all meetings without any overlaps.
A key observation is:
- if meetings are sorted by their start time, then
- we only need to check adjacent meetings for overlap
Why this works:
- if two meetings overlap, they must appear next to each other after sorting by start time
- there is no need to compare every pair
So by sorting once and doing a single pass, we can efficiently detect any conflict.
Steps
- Sort all meetings by their start time.
- Iterate through the sorted list starting from the second meeting:
- For each pair of adjacent meetings:
- let
i1be the previous meeting - let
i2be the current meeting
- let
- If
i1[1] > i2[0]:- the meetings overlap
- return
false
- If the loop finishes without finding any overlap:
- return
true
- return
Complexity
- Time complexity:
O(n log n) - Space complexity:
O(1)orO(n)depending on the sorting algorithm.
Things to watch for
Using the Wrong Overlap Condition
Meetings overlap when prev[1] > curr[0], not prev[1] >= curr[0]. If one meeting ends exactly when another starts, they do not overlap and can both be attended.
Forgetting to Sort Before Comparing Adjacent Meetings
The sorting approach only works when meetings are sorted by start time. Comparing adjacent meetings in an unsorted list will miss overlaps between non-adjacent intervals.
Python code example
from typing import List
class Solution:
def canAttendMeetings(self, intervals: List[List[int]]) -> bool:
intervals.sort(key=lambda i: i[0])
for i in range(1, len(intervals)):
i1 = intervals[i - 1]
i2 = intervals[i]
if i1[1] > i2[0]:
return False
return True
C++ code example
class Solution {
public:
bool canAttendMeetings(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end(), [](auto& x, auto& y) {
return x[0] < y[0];
});
for (int i = 1; i < intervals.size(); ++i) {
if (intervals[i][0] < intervals[i - 1][1]) {
return false;
}
}
return true;
}
};
Source and license
Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.