Back to Intervals
Easy
Meeting Rooms
Given an array of meeting time `intervals` where `intervals[i] = [starti, endi]`, determine if a person could attend all meetings.
Examples
Input:intervals = [[0,30],[5,10],[15,20]]
Output:false
The intervals [0,30] and [5,10] overlap, so a person cannot attend both.
Input:intervals = [[7,10],[2,4]]
Output:true
No intervals overlap, so a person can attend all meetings.
Constraints
0 <= intervals.length <= 10^4intervals[i].length == 20 <= starti < endi <= 10^6
Sort by Start Time
Approach
To check if any two meetings overlap, we can sort the intervals by their start times. Then, we iterate through the sorted intervals and check if the start time of the current meeting is earlier than the end time of the previous meeting. If `intervals[i][0] < intervals[i-1][1]`, they overlap, so we return false. If we finish checking all meetings without finding an overlap, we return true.
Complexity Analysis
Time Complexity
O(n log n)
Space Complexity
O(1)
Time complexity is O(n log n) because of sorting. The iteration takes O(n). Space complexity is O(1) assuming sorting is done in-place.
Solution.java
class Solution { public boolean canAttendMeetings(int[][] intervals) { if (intervals == null || intervals.length == 0) return true; // Sort intervals by start time Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0])); for (int i = 1; i < intervals.length; i++) { // If current meeting starts before the previous one ends if (intervals[i][0] < intervals[i - 1][1]) { return false; } } return true; }}