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.
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++
#include <bits/stdc++.h>
using namespace std;
static bool myCompare(pair< int , int > &p1, pair< int , int > &p2) {
if (p1.first == p2.first) {
return p1.second > p2.second;
}
return p1.first < p2.first;
}
bool areBookingsPossible( int arrival[],
int departure[], int n, int k)
{
vector<pair< int , int > > ans;
for ( int i = 0; i < n; i++) {
ans.push_back(make_pair(arrival[i], 1));
ans.push_back(make_pair(departure[i], 0));
}
sort(ans.begin(), ans.end(), myCompare);
int curr_active = 0, max_active = 0;
for ( int i = 0; i < ans.size(); i++) {
if (ans[i].second == 1) {
curr_active++;
max_active = max(max_active,
curr_active);
}
else
curr_active--;
}
return (k >= max_active);
}
int main()
{
int arrival[] = { 1, 3, 5 };
int departure[] = { 2, 6, 8 };
int n = sizeof (arrival) / sizeof (arrival[0]);
cout << (areBookingsPossible(arrival,
departure, n, 1)
? "Yes\n"
: "No\n" );
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class Pair {
int x;
int y;
public Pair( int x, int y)
{
this .x = x;
this .y = y;
}
}
class Compare {
static void compare(Pair arr[], int n)
{
Arrays.sort(arr, new Comparator<Pair>() {
@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];
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++;
}
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 (ans[i].y == 1 )
{
curr_active++;
max_active = Math.max(max_active,
curr_active);
}
else
curr_active--;
}
return (k >= max_active);
}
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" );
}
}
|
Python3
def areBookingsPossible(arrival, departure, n, k):
ans = []
for i in range ( 0 , n):
ans.append((arrival[i], 1 ))
ans.append((departure[i], 0 ))
ans.sort()
curr_active, max_active = 0 , 0
for i in range ( 0 , len (ans)):
if ans[i][ 1 ] = = 1 :
curr_active + = 1
max_active = max (max_active,
curr_active)
else :
curr_active - = 1
return k > = max_active
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" )
|
C#
using System;
using System.Linq;
using System.Collections.Generic;
class Pair {
public int x;
public int y;
public Pair( int x, int y)
{
this .x = x;
this .y = y;
}
}
class GFG
{
static bool areBookingsPossible( int [] arrival,
int [] departure,
int n, int k)
{
List<Pair> ans = new List<Pair>();
for ( int i = 0; i < 2 * n; i++)
ans.Add( new Pair(0, 0));
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++;
}
ans = ans.OrderBy(a => a.x).ToList();
int curr_active = 0, max_active = 0;
for ( int i = 0; i < 2 * n; i++)
{
if (ans[i].y == 1)
{
curr_active++;
max_active = Math.Max(max_active,
curr_active);
}
else
curr_active--;
}
return (k >= max_active);
}
public static void Main( string [] args)
{
int [] arrival = { 1, 3, 5 };
int [] departure = { 2, 6, 8 };
int n = arrival.Length;
Console.WriteLine(areBookingsPossible(arrival, departure, n, 1) ? "Yes" : "No" );
}
}
|
Javascript
<script>
function areBookingsPossible(arrival, departure, n, k)
{
var ans = [];
for ( var i = 0; i < n; i++) {
ans.push([arrival[i], 1]);
ans.push([departure[i], 0]);
}
ans.sort();
var curr_active = 0, max_active = 0;
for ( var i = 0; i < ans.length; i++) {
if (ans[i][1] == 1) {
curr_active++;
max_active = Math.max(max_active,
curr_active);
}
else
curr_active--;
}
return (k >= max_active);
}
var arrival = [1, 3, 5];
var departure = [2, 6, 8];
var n = arrival.length;
document.write(areBookingsPossible(arrival,
departure, n, 1)
? "Yes"
: "No" );
</script>
|
Complexity Analysis:
- 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++
#include <bits/stdc++.h>
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" ;
}
int main()
{
int arrival[] = { 1, 2, 3 };
int departure[] = { 2, 3, 4 };
int N = sizeof (arrival) / sizeof (arrival[0]);
int K = 1;
cout << (areBookingsPossible(
arrival, departure, K, N));
return 0;
}
|
Java
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" ;
}
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));
}
}
|
Python
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)
|
C#
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" ;
}
static void Main()
{
int []arrival = { 1, 2, 3 };
int []departure = { 2, 3, 4 };
int K = 1;
Console.Write(areBookingsPossible(
arrival, departure, K));
}
}
|
Javascript
<script>
function areBookingsPossible(A, B, K, N)
{
A.sort();
B.sort();
for (let i = 0; i < N; i++)
{
if (i + K < N && A[i + K] < B[i])
{
return "No" ;
}
}
return "Yes" ;
}
let arrival = [ 1, 2, 3 ];
let departure = [ 2, 3, 4 ];
let N = arrival.length;
let K = 1;
document.write(areBookingsPossible(
arrival, departure, K, N));
</script>
|
Complexity Analysis:
- Time Complexity: O(n Log n)
- Auxiliary Space: O(n) used by Python sort
Approach 3
The idea is to add the arrival and departure times of every booking to a list and then add it to another list of lists. After that, we will sort the list on the basis of increasing order of arrival times. In case, two bookings have the same arrival times, then we will sort it on the basis of early departure times.
Create a priority queue (min-heap), and traverse through each booking of the sorted array. For each traversal push the departure time in the priority queue and decrement the value of k (number of rooms). If the value of k becomes zero, it means we have no available rooms, then we will extract the minimum departure time of the room with the help of our priority queue.
We can accept the booking only and only if that minimum departure time is less than equal to the arrival time of the booking or else it’s impossible to accept the booking.
Following is the Implementation of above Approach –
C++
#include <bits/stdc++.h>
using namespace std;
bool cmp(vector< int > a, vector< int > b)
{
if (a[0] == b[0])
return a[1] < b[1];
return a[0] < b[0];
}
bool areBookingsPossible(vector< int > arrival,
vector< int > departure, int n,
int k)
{
vector<vector< int > > list;
for ( int i = 0; i < arrival.size(); i++) {
vector< int > li;
li.push_back(arrival[i]);
li.push_back(departure[i]);
list.push_back(li);
}
sort(list.begin(), list.end(), cmp);
vector< int > pq;
for ( int i = 0; i < list.size(); i++) {
if (list[i][0] != list[i][1]) {
if (k > 0) {
k--;
pq.push_back(list[i][1]);
sort(pq.begin(), pq.end());
}
else {
if (pq[0] <= list[i][0]) {
pq.erase(pq.begin());
pq.push_back(list[i][1]);
sort(pq.begin(), pq.end());
}
else {
return false ;
}
}
}
}
return true ;
}
int main()
{
vector< int > arrival = { 1, 3, 5 };
vector< int > departure = { 2, 6, 8 };
int n = arrival.size();
cout << (areBookingsPossible(arrival, departure, n, 1)
? "Yes"
: "No" );
}
|
Java
import java.util.*;
class GFG {
public static boolean areBookingsPossible( int arrival[], int departure[], int n, int k) {
List<List<Integer>> list = new ArrayList<>();
for ( int i = 0 ; i < arrival.length; i++) {
List<Integer> li = new ArrayList<>();
li.add(arrival[i]);
li.add(departure[i]);
list.add(li);
}
Collections.sort(list, new Comp());
PriorityQueue<Integer> pq = new PriorityQueue<>();
for ( int i = 0 ; i < list.size(); i++) {
if (list.get(i).get( 0 ) != list.get(i).get( 1 )) {
if (k > 0 ) {
k--;
pq.add(list.get(i).get( 1 ));
} else {
if (pq.peek() <= list.get(i).get( 0 )) {
pq.remove();
pq.add(list.get(i).get( 1 ));
} else {
return false ;
}
}
}
}
return true ;
}
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" );
}
}
class Comp implements Comparator<List<Integer>> {
public int compare (List<Integer> l1, List<Integer> l2) {
if (l1.get( 0 ) < l2.get( 0 )) {
return - 1 ;
} else if (l1.get( 0 ) == l2.get( 0 )) {
if (l1.get( 1 ) < l2.get( 1 )) {
return - 1 ;
} else {
return 1 ;
}
} else {
return 1 ;
}
}
}
|
Python3
def areBookingsPossible(arrival, departure, n, k):
list1 = []
for i in range ( len (arrival)):
li = []
li.append(arrival[i])
li.append(departure[i])
list1.append(li)
list1.sort()
pq = []
for i in range ( len (list1)):
if (list1[i][ 0 ] ! = list1[i][ 1 ]):
if (k > 0 ):
k - = 1
pq.append(list1[i][ 1 ])
pq.sort()
else :
if (pq[ 0 ] < = list1[i][ 0 ]):
pq.pop( 0 )
pq.append(list1[i][ 1 ])
pq.sort()
else :
return False
return True
arrival = [ 1 , 3 , 5 ]
departure = [ 2 , 6 , 8 ]
n = len (arrival)
if areBookingsPossible(arrival, departure, n, 1 ):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Linq;
using System.Collections.Generic;
class GFG {
public static bool areBookingsPossible( int [] arrival,
int [] departure,
int n, int k)
{
List<List< int > > list = new List<List< int > >();
for ( int i = 0; i < arrival.Length; i++) {
List< int > li = new List< int >();
li.Add(arrival[i]);
li.Add(departure[i]);
list.Add(li);
}
list = list.OrderBy(l = > l[0])
.ThenBy(l = > l[1])
.ToList();
List< int > pq = new List< int >();
for ( int i = 0; i < list.Count; i++) {
if (list[i][0] != list[i][1]) {
if (k > 0) {
k--;
pq.Add(list[i][1]);
pq = pq.OrderBy(p = > p).ToList();
}
else {
if (pq[0] <= list[i][0]) {
pq.RemoveAt(0);
pq.Add(list[i][1]);
pq = pq.OrderBy(p = > p).ToList();
}
else {
return false ;
}
}
}
}
return true ;
}
public static void Main( string [] args)
{
int [] arrival = { 1, 3, 5 };
int [] departure = { 2, 6, 8 };
int n = arrival.Length;
Console.WriteLine(
areBookingsPossible(arrival, departure, n, 1)
? "Yes"
: "No" );
}
}
|
Javascript
function cmp(a, b)
{
if (a[0] == b[0])
return a[1] < b[1];
return a[0] < b[0];
}
function areBookingsPossible(arrival, departure, n,
k)
{
let list = [];
for ( var i = 0; i < arrival.length; i++) {
let li = [];
li.push(arrival[i]);
li.push(departure[i]);
list.push(li);
}
list.sort(cmp)
let pq = [];
for ( var i = 0; i < list.length; i++) {
if (list[i][0] != list[i][1]) {
if (k > 0) {
k--;
pq.push(list[i][1]);
pq.sort( function (a, b) { return a > b})
}
else {
if (pq[0] <= list[i][0]) {
pq.shift()
pq.push(list[i][1]);
pq.sort( function (a, b) { return a > b})
}
else {
return false ;
}
}
}
}
return true ;
}
let arrival = [ 1, 3, 5 ];
let departure = [ 2, 6, 8 ];
let n = arrival.length;
console.log (areBookingsPossible(arrival, departure, n, 1)
? "Yes"
: "No" );
|
Complexity Analysis:
- Time Complexity: O(n Log n)
- Auxiliary Space: O(k)