Meeting Rooms
Problem
intervals[i] = [start, end], where a meeting
occupies the half-open range [start, end). Return true if one
person could attend all of them, i.e. no two meetings overlap. A meeting that ends
at time t does not clash with one that starts at t.intervals = [[0,30],[5,10],[15,20]]Outputfalseintervals = [[7,10],[2,4]]Outputtrueintervals = [[1,5],[5,8]]Outputtrue0 ≤ intervals.length ≤ 104 · 0 ≤ start < end ≤ 106
Try it yourself
class Solution {
public boolean canAttendMeetings(int[][] intervals) {
}
}
i clears meeting i-1, it clears
every earlier one too.Instinct See [start, end] pairs, meetings, bookings or the word "overlap"? Sort by an endpoint, then sweep left to right carrying one running fact.
Memory hack Sort, then sweep - start time to merge, end time to choose, +1/-1 events to count the crowd.
Open the Intervals & Line Sweep guide →Approaches
Brute ForceCheck Every Pair
O(n2)Space O(1)Two half-open ranges [a,b) and [c,d) overlap exactly
when a < d and c < b. Test that condition for
every pair; any hit means the schedule is impossible.
public boolean canAttendMeetings(int[][] intervals) { int n = intervals.length; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { boolean overlap = intervals[i][0] < intervals[j][1] && intervals[j][0] < intervals[i][1]; if (overlap) return false; } } return true; }
Direct and correct, but quadratic for 104 meetings.
OptimalSort by Start, Compare Neighbours
O(n log n)Space O(log n)Sort by start time. Walking left to right, a clash exists exactly when some meeting starts before the previous one ends. Because starts are non-decreasing, checking adjacent pairs is enough.
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; // starts before prev ends } return true; }
Dry runintervals = [[0,30],[5,10],[15,20]]
- sorted0-305-1015-20order by start
- i=10-30p5-10i15-205 < 30 → false
Sorting dominates; one linear pass does the rest.
At a glance
| Level | Approach | Time | Space |
|---|---|---|---|
| Brute Force | Check Every Pair | O(n2) | O(1) |
| Optimal | Sort by Start, Compare Neighbours | O(n log n) | O(log n) |
- Using
<=— back-to-back meetings like [1,5],[5,8] are fine. - Comparing only with the first meeting instead of the previous one.
- Forgetting the empty and single-meeting cases (both
true).
- Confirm whether intervals are half-open or closed before coding.
- Explain why adjacent checks suffice after sorting.
- Expect the follow-up: how many rooms are needed (Meeting Rooms II).