Meeting Rooms LeetCode

Imagine multiple meetings are scheduled throughout the day, each represented by a time interval. The task is to determine if a person can attend all these meetings without overlaps. For instance, if we have meetings from 9:00 to 10:00 a.m. and another from 10:30 to 11:30 a.m., we could attend both as there’s a gap. This problem is crucial for time management and scheduling in various scenarios, from business meetings to event planning.

Problem statement

Given an array of meeting intervals, intervals where intervals[i] = [starti, endi], determine if a person can attend all meetings without any overlap.

Constraints:

  • 00 \leq intervals.length 103\leq 10^3

  • intervals[i].length ==2== 2

  • 00 \leq startistart_{i} << endiend_{i} 106\leq 10^6

Now, let’s look at some examples to better understand this problem:

canvasAnimation-image
1 of 2

Knowledge test

Let’s take a short quiz to ensure we understand the problem correctly.

1

Can two meetings with times [[0, 10], [11, 12]] be scheduled without conflicts?

A)

Yes

B)

No

Question 1 of 30 attempted

Algorithm

We can solve this problem by sorting the meetings based on their start times. Then, we iterate through the meetings and check if the current meeting starts before the previous meeting ends. If so, there's a conflict, and attending all meetings is impossible.

Now, let’s look at the following illustration to get a better understanding of the solution:

canvasAnimation-image
1 of 6

Coding example

Now, let’s look at the solution for this coding challenge.

def attend_all_meetings(intervals):
# Sort meetings by start time
intervals.sort(key=lambda x: x[0])
for i in range(len(intervals) - 1):
# Check for overlaps
if intervals[i][1] > intervals[i + 1][0]:
return False
return True
#Driver code
def main():
# Test cases
test_cases = [
[[0, 1], [2, 4], [1, 3], [5, 6]],
[[7, 10], [2, 4], [1, 3], [5, 6]],
[[0, 1], [1, 2], [2, 3], [3, 4]],
[[1, 2], [2, 3], [1, 3], [3, 4]],
[[0, 5], [1, 2], [3, 4], [6, 7]],
[[7, 10], [2, 4]]
]
for i, meetings in enumerate(test_cases):
print(f"Test Case {i+1}:",test_cases[i])
if attend_all_meetings(meetings):
print("You can attend all meetings without conflicts.\n")
else:
print("There are conflicts in the meeting schedule.\n")
if __name__ == "__main__":
main()
Meeting Rooms in Python

Time complexity

Sorting the meetings takes O(nlogn)O(n log n) time, where n n is the number of meetings. The loop iterates through the meetings once, taking O(n)O(n) time. Overall, the time complexity is dominated by sorting and is considered O(nlogn)O(n log n).

Space complexity

The algorithm uses a constant extra space for variables, regardless of the number of meetings. Therefore, the space complexity is O(1)O(1).

Copyright ©2024 Educative, Inc. All rights reserved