You are given an array of time intervals where some people arrive and leave a waiting room. Each interval is represented by a pair of integers [start, end]
, where start
indicates the time of arrival and end
the time of departure.
You need to determine the minimum number of chairs required in the waiting room so that no one has to wait standing.
Example:
Input: intervals = [[1, 4], [2, 3], [3, 6], [5, 7]]
Output: 3
O(n log n)
, where n
is the number of intervals.O(n)
.Thus, the overall time complexity is O(n log n)
.
def min_chairs_required(intervals):
if not intervals:
return 0
arrivals = sorted([interval[0] for interval in intervals])
departures = sorted([interval[1] for interval in intervals])
min_chairs = 0
current_chairs = 0
i, j = 0, 0
while i < len(arrivals) and j < len(departures):
if arrivals[i] <= departures[j]:
current_chairs += 1
min_chairs = max(min_chairs, current_chairs)
i += 1
else:
current_chairs -= 1
j += 1
return min_chairs
# Example usage:
intervals = [[1, 4], [2, 3], [3, 6], [5, 7]]
print(min_chairs_required(intervals)) # Output: 3
This function computes the minimum number of chairs required in the waiting room based on the given time intervals.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?