Meeting Rooms
Meeting Rooms is a easy intervals problem solved with the basics pattern.
The best approach, optimal (sort by start, check neighbours), runs in O(n log n) time and O(log n) space.
Below are 2 approaches in Java, from check every pair up.
Problem
Given meeting times as [start, end) intervals, decide whether one person can attend all of them, meaning no two meetings overlap.
Examples
Example 1
- Input
intervals = [[0, 30], [5, 10], [15, 20]]- Output
false- Why
- [0, 30] clashes with both others.
Example 2
- Input
intervals = [[7, 10], [2, 4]]- Output
true
Constraints
0 <= intervals.length <= 10^4- Meetings are [start, end); one ending at 5 and another starting at 5 do not clash.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the Java code.
| Approach | Time | Space |
|---|---|---|
| Check every pair | O(n²) | O(1) |
| Optimal (sort by start, check neighbours) | O(n log n) | O(log n) |
1Check every pair
O(n²)O(1)Two meetings clash when each starts before the other ends. Compare all pairs.
- For all i < j: if a.start < b.end && b.start < a.end, return false.
class Solution {
public boolean canAttendMeetings(int[][] intervals) {
for (int i = 0; i < intervals.length; i++)
for (int j = i + 1; j < intervals.length; j++)
if (intervals[i][0] < intervals[j][1] && intervals[j][0] < intervals[i][1]) return false;
return true;
}
}2Optimal (sort by start, check neighbours)
O(n log n)O(log n)Sort by start. If any meeting starts before the previous one ends, there is a clash.
- Sort by start.
- For i >= 1: if intervals[i][0] < intervals[i - 1][1], return false.
class Solution {
public boolean canAttendMeetings(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
for (int i = 1; i < intervals.length; i++)
if (intervals[i][0] < intervals[i - 1][1]) return false;
return true;
}
}Edge cases to test
- No meetings
- Back-to-back meetings (end == next start)
Hints
Hint 1
After sorting by start time, a clash can only happen between neighbours.
FAQ
What is the best time complexity for Meeting Rooms?
Optimal (sort by start, check neighbours) runs in O(n log n) time and O(log n) extra space.
Which pattern does Meeting Rooms use?
It is a intervals problem that uses the basics pattern. Other problems with the same pattern: Detect overlap unsorted, Detect overlap sorted intervals, Interval List Intersections.
Is there a brute force solution for Meeting Rooms?
Yes. Check every pair takes O(n²) time and O(1) space. Two meetings clash when each starts before the other ends.
Which edge cases should I test for Meeting Rooms?
No meetings; Back-to-back meetings (end == next start).