Meeting Rooms easy
Problem Statement
Given an array of meeting time intervals where intervals[i] = [starti, endi]
, determine if a person could attend all meetings.
Example 1:
Input: intervals = [[0,30],[5,10],[15,20]] Output: false Explanation: The person can not attend both intervals [5,10] and [15,20] because they overlap.
Example 2:
Input: intervals = [[7,10],[2,4]] Output: true Explanation: No two meetings overlap.
Steps:
- Sort the intervals: Sort the intervals based on their start times. This makes it easier to check for overlaps.
- Iterate and compare: Iterate through the sorted intervals. For each interval, compare its start time with the end time of the previous interval. If the current interval's start time is less than or equal to the previous interval's end time, there's an overlap.
- Return the result: If any overlap is found, return
False
. Otherwise, returnTrue
.
Explanation:
The key idea is that if we sort the meetings by their start times, we can easily detect overlaps by simply comparing the end time of the previous meeting with the start time of the current meeting. If the start time of the current meeting is before the end time of the previous meeting, they overlap. We only need to check consecutive pairs since if there's a gap, any other meetings won't overlap with the current meeting.
Code:
def canAttendMeetings(intervals):
"""
Determines if a person can attend all meetings without any overlaps.
Args:
intervals: A list of meeting time intervals, where each interval is a list of two integers [start, end].
Returns:
True if a person can attend all meetings, False otherwise.
"""
if not intervals: # Handle empty input
return True
# Sort intervals by start time
intervals.sort()
# Iterate and check for overlaps
for i in range(1, len(intervals)):
if intervals[i][0] < intervals[i - 1][1]: #Check for overlap
return False
return True
Complexity:
- Time Complexity: O(n log n), dominated by the sorting step.
- Space Complexity: O(1) (in-place sorting; if we use a different sorting algorithm, it might require O(n) extra space).