This problem asks whether a person can attend all meetings given a list of meeting time intervals. Each interval is represented as a pair [start_i, end_i]
, where start_i
is the start time and end_i
is the end time of the meeting. The person can attend all meetings if and only if no two meetings overlap.
The optimal approach involves sorting and then checking for overlaps.
Algorithm:
Sort the intervals: Sort the intervals by their start times in ascending order. This step allows us to efficiently check for overlaps in a single pass.
Check for overlaps: Iterate through the sorted intervals, comparing the end time of the current meeting with the start time of the next meeting. If the end time of the current meeting is greater than or equal to the start time of the next meeting, there's an overlap, and the person cannot attend all meetings. Otherwise, continue to the next pair.
Return the result: If no overlaps are found after checking all pairs, the person can attend all meetings.
Time Complexity: O(N log N), dominated by the sorting step. The iterative check for overlaps takes O(N) time.
Space Complexity: O(1) (in-place sort can be used, or if you use a separate sorted array, then O(N) for the extra space).
Code Explanation (using Python as an example):
class Solution:
def canAttendMeetings(self, intervals: List[List[int]]) -> bool:
intervals.sort() #Sort the intervals based on start time. Python's sort is Timsort, O(NlogN)
for i in range(len(intervals) - 1): #Iterate through all but the last interval
if intervals[i][1] > intervals[i+1][0]: #Check for overlap: if the end time of current is > start time of next
return False #Overlap found, cannot attend all meetings
return True #No overlaps found
The Python code directly implements the algorithm. The intervals.sort()
line sorts the intervals in place based on the start time of each interval (the first element in each sublist). The loop then efficiently checks for overlaps between consecutive intervals.
Code Explanation (Java):
class Solution {
public boolean canAttendMeetings(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> a[0] - b[0]); //Sort using a comparator, O(NlogN)
for (int i = 1; i < intervals.length; ++i) { //Iterate through all but the first interval
if (intervals[i - 1][1] > intervals[i][0]) { //Check for overlap
return false;
}
}
return true;
}
}
The Java code is very similar, using Arrays.sort
with a lambda expression as the comparator to sort the intervals by start time. The loop checks for overlaps in the same way as the Python code. Other languages' implementations follow a similar pattern.