Meeting Rooms
Can one person attend all meetings? Sort by start and check adjacent overlaps — classic interval warm-up.
- dsa
- intervals
- interview
- Meta
- Amazon
The problem
Given an array of meeting time intervals intervals where intervals[i] = [startᵢ, endᵢ], return true if a person can attend all meetings (no overlaps). Touching endpoints (end == next start) is usually OK — not an overlap.
Input: [[0,30],[5,10],[15,20]]
Output: false
Input: [[7,10],[2,4]]
Output: true
Brute force
Check every pair for overlap. Overlap if a.start < b.end && b.start < a.end (adjust for closed/open).
function canAttendMeetingsBrute(intervals: number[][]): boolean {
for (let i = 0; i < intervals.length; i++) {
for (let j = i + 1; j < intervals.length; j++) {
const [s1, e1] = intervals[i];
const [s2, e2] = intervals[j];
if (s1 < e2 && s2 < e1) return false;
}
}
return true;
}
| Time | O(n²) |
| Space | O(1) |
Optimal: sort by start
After sorting, only adjacent meetings can be the “first” conflict in sequence — if any overlap exists, some adjacent pair in sorted order will overlap.
function canAttendMeetings(intervals: number[][]): boolean {
intervals.sort((a, b) => a[0] - b[0]);
for (let i = 1; i < intervals.length; i++) {
if (intervals[i][0] < intervals[i - 1][1]) {
return false;
}
}
return true;
}
| Time | O(n log n) |
| Space | O(1) or O(n) depending on sort |
Why adjacent is enough
Sorted by start: if A overlaps C with B in between, A also overlaps B (B starts ≥ A.start and before A ends). One linear scan catches it.
Edge cases
- Empty / single meeting → true
- Touching:
[1,5]and[5,10]→ true with strict<on starts - Nested intervals → false
- Unsorted input — always sort
Common bugs
- Sorting by end instead of start (works for some greedy problems, not this check)
- Using
<=vs<incorrectly for half-open intervals - Mutating caller’s array without clarifying
Interview delivery
- Clarify endpoint touching.
- Sort by start.
- Scan adjacent.
- O(n log n).
- Bridge to Meeting Rooms II (min rooms).
Related
Overlap predicate
Two intervals [s1,e1], [s2,e2] overlap if they share any positive-length time. With half-open style or “touching is ok”, condition for conflict after sort is nextStart < prevEnd.
Sorting stability
JS sort is not guaranteed stable historically (modern V8 is stable). Stability doesn’t matter here — we only compare adjacent starts after ordering by start.
Bridge to harder interval problems
| Problem | Goal |
|---|---|
| Meeting Rooms | any overlap? |
| Meeting Rooms II | peak concurrency |
| Merge Intervals | union ranges |
| Non-overlapping | min removals |
All start with “sort the intervals.” That sentence alone is half the pattern.