Number line meetings sorted by start · bottom lane: your calendar, one room · the line marks i1.end
public boolean canAttendMeetings(List<Interval> intervals) { intervals.sort((a, b) -> Integer.compare(a.start, b.start)); for (int i = 1; i < intervals.size(); i++) { Interval i1 = intervals.get(i - 1); Interval i2 = intervals.get(i); if (i1.end > i2.start) { // overlap return false; } } return true;}
- i
- —
- i1
- —
- i2
- —
Why it works
- Brute force checks every pair of meetings for overlap: O(n²) comparisons.
- After sorting by start, only neighbours can clash first. If meeting
iclears meetingi − 1, it also clears every earlier one, because those all ended by the timei − 1started. So one pass over adjacent pairs decides it. - Cost: O(n log n) for the sort, then n − 1 comparisons. The sort is in place, so O(1) extra space (
List.sortis a merge sort, TimSort, which may use O(n) scratch). - Pitfall: use a strict
>.[1,3]then[3,6]is back to back, not a clash. And an empty list, or a single meeting, is attendable. - Follow-up: Meeting Rooms II (253) asks how many rooms you need when meetings may overlap: sweep the starts and ends and track the peak.