Related Articles

# Find if k bookings possible with given arrival and departure times

• Difficulty Level : Medium
• Last Updated : 14 Jun, 2021

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.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Examples:

```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.```

Approach 1
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 implementation of the above approach:

## C++

 `// C++ implementation of the above approach``#include ``using` `namespace` `std;` `bool` `areBookingsPossible(``int` `arrival[],``                         ``int` `departure[], ``int` `n, ``int` `k)``{``    ``vector > ans;` `    ``// create a common vector both arrivals``    ``// and departures.``    ``for` `(``int` `i = 0; i < n; i++) {``        ``ans.push_back(make_pair(arrival[i], 1));``        ``ans.push_back(make_pair(departure[i], 0));``    ``}` `    ``// sort the vector``    ``sort(ans.begin(), ans.end());` `    ``int` `curr_active = 0, max_active = 0;` `    ``for` `(``int` `i = 0; i < ans.size(); i++) {` `        ``// if new arrival, increment current``        ``// guests count and update max active``        ``// guests so far``        ``if` `(ans[i].second == 1) {``            ``curr_active++;``            ``max_active = max(max_active,``                             ``curr_active);``        ``}` `        ``// if a guest departs, decrement``        ``// current guests count.``        ``else``            ``curr_active--;``    ``}` `    ``// if max active guests at any instant``    ``// were more than the available rooms,``    ``// return false. Else return true.``    ``return` `(k >= max_active);``}` `int` `main()``{``    ``int` `arrival[] = { 1, 3, 5 };``    ``int` `departure[] = { 2, 6, 8 };``    ``int` `n = ``sizeof``(arrival) / ``sizeof``(arrival);``    ``cout << (areBookingsPossible(arrival,``                                 ``departure, n, 1)``                 ``? ``"Yes\n"``                 ``: ``"No\n"``);``    ``return` `0;``}`

## Java

 `// Java implementation of the above approach``import` `java.io.*;``import` `java.util.*;` `// User defined Pair class``class` `Pair {``  ``int` `x;``  ``int` `y;` `  ``// Constructor``  ``public` `Pair(``int` `x, ``int` `y)``  ``{``    ``this``.x = x;``    ``this``.y = y;``  ``}``}` `// class to define user defined conparator``class` `Compare {` `  ``static` `void` `compare(Pair arr[], ``int` `n)``  ``{` `    ``// Comparator to sort the pair according to second element``    ``Arrays.sort(arr, ``new` `Comparator() {``      ``@Override` `public` `int` `compare(Pair p1, Pair p2)``      ``{``        ``return` `p1.x - p2.x;``      ``}``    ``});``  ``}``}` `class` `GFG``{``  ``static` `boolean` `areBookingsPossible(``int` `arrival[],``                                     ``int` `departure[],``                                     ``int` `n, ``int` `k)``  ``{``    ``Pair ans[] = ``new` `Pair[``2``*n];` `    ``// create a common vector both arrivals``    ``// and departures.``    ``int` `j = ``0``;``    ``for` `(``int` `i = ``0``; i < n; i++)``    ``{``      ``ans[i + j] = ``new` `Pair(arrival[i], ``1``);``      ``ans[i + j + ``1``] = ``new` `Pair(departure[i], ``0``);``      ``j++;``    ``}` `    ``// sort the vector``    ``Compare obj = ``new` `Compare();``    ``obj.compare(ans, ``2` `* n);     ``    ``int` `curr_active = ``0``, max_active = ``0``;    ``    ``for` `(``int` `i = ``0``; i < ``2` `* n; i++)``    ``{` `      ``// if new arrival, increment current``      ``// guests count and update max active``      ``// guests so far``      ``if` `(ans[i].y == ``1``)``      ``{``        ``curr_active++;``        ``max_active = Math.max(max_active,``                              ``curr_active);``      ``}` `      ``// if a guest departs, decrement``      ``// current guests count.``      ``else``        ``curr_active--;``    ``}` `    ``// if max active guests at any instant``    ``// were more than the available rooms,``    ``// return false. Else return true.``    ``return` `(k >= max_active);``  ``}` `  ``// Driver code``  ``public` `static` `void` `main(String[] args)``  ``{``    ``int` `arrival[] = { ``1``, ``3``, ``5` `};``    ``int` `departure[] = { ``2``, ``6``, ``8` `};``    ``int` `n = arrival.length;``    ``System.out.println(areBookingsPossible(arrival, departure, n, ``1``) ? ``"Yes"` `: ``"No"``);``  ``}``}` `// This code is contributed by divyeshrabadiya07`

## Python3

 `# 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):``        ``ans.append((arrival[i], ``1``))``        ``ans.append((departure[i], ``0``))` `    ``# Sort the vector``    ``ans.sort()``    ``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``] ``=``=` `1``:``            ``curr_active ``+``=` `1``            ``max_active ``=` `max``(max_active,``                             ``curr_active)` `        ``# if a guest departs, decrement``        ``# current guests count.``        ``else``:``            ``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)``    ` `    ``if` `areBookingsPossible(arrival,``                           ``departure, n, ``1``):``        ``print``(``"Yes"``)``    ``else``:``        ``print``(``"No"``)``    ` `# This code is contributed by Rituraj Jain`

## Javascript

 ``
Output
`No`

Time Complexity: O(n Log n)
Auxiliary Space: O(n)

Approach 2
The idea is to simply sort the 2 arrays (Array for arrival dates and Array for departure dates) first.
Now, the next step would be to check how many overlaps are present in one particular range. If the number of overlaps are greater than the number of rooms, we can say that we have less rooms to accommodate guests.

So, for a particular range where arrival date(ith of Arrival array) being the start date and departure date(ith of departure array) being the end date, overlap can be only possible if the next arrival dates(from i+1th) are less than end date of the range and greater than or equal to start date of the range (Since this is a sorted array, we don’t need to take care about the latter condition).

Considering the fact, that we have sorted array, we directly need to check if the next Kth (i+Kth) arrival date falls in the range, if it does, all the dates before that arrival date will also fall in the taken range, resulting in K+1 overlaps with the range in question, hence exceeding the number of rooms.

Following is the Implementation of above Approach –

## C++

 `// C++ code implementation of the above approach``#include ``using` `namespace` `std;` `string areBookingsPossible(``int` `A[], ``int` `B[],``                           ``int` `K, ``int` `N)``{``    ``sort(A, A + N);``    ``sort(B, B + N);``    ` `    ``for``(``int` `i = 0; i < N; i++)``    ``{``        ``if` `(i + K < N && A[i + K] < B[i])``        ``{``            ``return` `"No"``;``        ``}``    ``}``    ``return` `"Yes"``;``}` `// Driver Code``int` `main()``{``    ``int` `arrival[] = { 1, 2, 3 };``    ``int` `departure[] = { 2, 3, 4 };``    ``int` `N = ``sizeof``(arrival) / ``sizeof``(arrival);``    ``int` `K = 1;``  ` `    ``cout << (areBookingsPossible(``        ``arrival, departure, K, N));` `    ``return` `0;``}` `// This code is contributed by rag2127`

## Java

 `// Java code implementation of the above approach``import` `java.util.*;``class` `GFG``{``     ` `static` `String areBookingsPossible(``int` `[]A, ``int` `[]B,``                                  ``int` `K)``{``    ``Arrays.sort(A);``    ``Arrays.sort(B);  ``    ``for``(``int` `i = ``0``; i < A.length; i++)``    ``{``        ``if` `(i + K < A.length && A[i + K] < B[i])``        ``{``            ``return` `"No"``;``        ``}``    ``}``    ``return` `"Yes"``;``}`` ` `// Driver Code``public` `static` `void` `main(String []s)``{``    ``int` `[]arrival = { ``1``, ``2``, ``3` `};``    ``int` `[]departure = { ``2``, ``3``, ``4` `};``    ``int` `K = ``1``;    ``    ``System.out.print(areBookingsPossible(``        ``arrival, departure, K));``}``}` `// This code is contributed by Pratham76`

## Python

 `# Python Code Implementation of the above approach``def` `areBookingsPossible(A, B, K):``        ``A.sort()``        ``B.sort()``        ``for` `i ``in` `range``(``len``(A)):``            ``if` `i``+``K < ``len``(A) ``and` `A[i``+``K] < B[i] :``                ``return` `"No"``        ``return` `"Yes"` `if` `__name__ ``=``=` `"__main__"``:``    ``arrival ``=` `[``1``, ``2``, ``3``] ``    ``departure ``=` `[``2``, ``3``, ``4``]  ``    ``K ``=` `1``    ``print` `areBookingsPossible(arrival,departure,K)` `# This code was contributed by Vidhi Modi`

## C#

 `// C# code implementation of the above approach``using` `System;` `class` `GFG{``    ` `static` `string` `areBookingsPossible(``int` `[]A, ``int` `[]B,``                                  ``int` `K)``{``    ``Array.Sort(A);``    ``Array.Sort(B);``    ` `    ``for``(``int` `i = 0; i < A.Length; i++)``    ``{``        ``if` `(i + K < A.Length && A[i + K] < B[i])``        ``{``            ``return` `"No"``;``        ``}``    ``}``    ``return` `"Yes"``;``}` `// Driver Code``static` `void` `Main()``{``    ``int` `[]arrival = { 1, 2, 3 };``    ``int` `[]departure = { 2, 3, 4 };``    ``int` `K = 1;``    ` `    ``Console.Write(areBookingsPossible(``        ``arrival, departure, K));``}``}` `// This code is contributed by rutvik_56`

## Javascript

 ``
Output
`Yes`

Time Complexity: O(n Log n)
Auxiliary Space: O(n) used by Python sort

My Personal Notes arrow_drop_up