Given an integer representing the capacity of a cyber cafe and a sequence representing entry/exit logs of customers, find the total number of customers who could not get any computer.

The first occurrence in the given sequence indicates the arrival, and the second occurrence indicates the departure for a customer. A customer cannot be serviced when the cafe capacity is full (when all computers are allocated).

 
For example,

Input:
 
sequence = “ABCDDCEFFEBGAG”
capacity = 3
 
Output: 2 (Customers ‘D’ and ‘F’ left unattended)
 
 
Input:
 
sequence = “ABCDDCBEFFEGAG”
capacity = 2
 
Output: 3 (Customers ‘C’, ‘D’, and ‘F’ left unattended)

The idea is to traverse the given sequence and keep track of customers who are currently inside the cyber cafe, irrespective of whether they have been allocated computers or not. We also keep track of the customers who were allocated computers. Now, two cases arise for each record:

  • When a customer arrives at the cyber cafe, mark the customer as visited and allocate a computer if available; if no computer is available, increment the count of unattended customers.
  • When a customer leaves the cafe, mark the customer as unvisited and deallocate the computer.

Finally, after every record is processed, return the unattended customers count. Following is the implementation in C++, Java, and Python based on the above idea:

C++


Download  Run Code

Output:

2

Java


Download  Run Code

Output:

2

Python


Download  Run Code

Output:

2

The time complexity of the above solution is O(n), and requires O(n) extra space, where n is the total number of customers.