Intuition
After sorting meetings by start time, the only possible conflicts are between consecutive meetings. If any meeting starts before the previous one ends, they overlap.
Explanation
Why adjacent-only
Sort the intervals by start time. Now they appear in chronological order, so a meeting can only clash with the one immediately before it — if it started before an earlier meeting, sorting would have placed it earlier. Thus a single left-to-right pass suffices.
intervals.sort()
for i in 1..n-1:
if intervals[i].start < intervals[i-1].end: return False
return True
Note end == start is allowed (back-to-back meetings don't overlap).
Worked example
[[0,30],[5,10],[15,20]] sorted stays the same: 5 < 30 → overlap → false.
Complexity
- Time: O(n log n) for the sort.
- Space: O(1) extra (or O(n) for the sort).
Implementation
import java.util.Arrays;
class Solution {
public boolean canAttendMeetings(int[][] intervals) {
Arrays.sort(intervals, (x, y) -> Integer.compare(x[0], y[0]));
for (int i = 1; i < intervals.length; i++) {
if (intervals[i][0] < intervals[i - 1][1]) {
return false;
}
}
return true;
}
}