A hotel manager has to process N advance bookings of rooms for the next season. His hotel has K rooms. Bookings contain an arrival date and a departure date. He wants to find out whether there are enough rooms in the hotel to satisfy the demand.
The idea is to sort the arrays and keep track of overlaps.
Input : Arrivals : [1 3 5] Departures : [2 6 8] K: 1 Output: False Hotel manager needs at least two rooms as the second and third intervals overlap.
The idea is store arrival and departure times in an auxiliary array with an additional marker to indicate whether the time is arrival or departure. Now sort the array. Process the sorted array, for every arrival increment active bookings. And for every departure, decrement. Keep track of maximum active bookings. If the count of active bookings at any moment is more than k, then return false. Else return true.
Below is the code for above approach.
# Python3 code for the above approach.
def areBookingsPossible(arrival, departure, n, k):
ans = 
# Create a common vector both arrivals
# and departures.
for i in range(0, n):
# Sort the vector
curr_active, max_active = 0, 0
for i in range(0, len(ans)):
# If new arrival, increment current
# guests count and update max active
# guests so far
if ans[i] == 1:
curr_active += 1
max_active = max(max_active,
# if a guest departs, decrement
# current guests count.
curr_active -= 1
# If max active guests at any instant
# were more than the available rooms,
# return false. Else return true.
return k >= max_active
# Driver Code
if __name__ == “__main__”:
arrival = [1, 3, 5]
departure = [2, 6, 8]
n = len(arrival)
departure, n, 1):
# This code is contributed by Rituraj Jain
Time Complexity: O(n Log n)
Auxiliary Space: O(n)