Panda Guru LogoPanda
Guru

Amazon | SDE2 | OA

Round 1

Questions: Amazon Web Services (AWS) is a cloud computing platform with multiple servers. One of the servers is assigned to serve customer requests. There are n customer requests placed sequentially in a queue, where the ith request has a maximum waiting time denoted by wait[i]. That is, if the ith request is not served within wait[i] seconds, then the request expires and it is removed from the queue. The server processes the request following the First In First Out (FIFO) principle. The 1st request is processed first, and the nth request is served last. At each second, the first request in the queue is processed. At the next second, the processed request and any expired requests are removed from the queue.

Given the maximum waiting time of each request denoted by the array wait, find the number of requests present in the queue at every second until it is empty.

Note:

Example The number of requests is n = 4, and their maximum wait times are wait = [2, 2, 3, 1].

image

The answer is [4, 2, 1, 0].

Function Description Complete the function findRequestsInQueue in the editor below.

findRequestsInQueue has the following parameter:

Returns int[]: the number of requests in the queue at each instant until the queue becomes empty.

Constraints

Sample Case 0 Sample Input For Custom Testing

STDIN Function ----- ------ 4 → wait[] size n = 4 3 → wait = [3, 1, 2, 1] 1 2 1

Sample Output

4 1 0

Explanation

Sample Case 1 Sample Input For Custom Testing

STDIN Function ----- ------ 3 → wait[] size n = 3 4 → wait = [4, 4, 4] 4 4

Sample Output

3 2 1 0

Explanation

Working Solution (5/10 test cases passed)

public static List<Integer> processRequests(int[] wait) { // Create a queue to store the remaining wait times for each request Queue<Integer> queue = new LinkedList<>(); // Add all requests' wait times to the queue for (int w : wait) { queue.offer(w); } int second = 0; List<Integer> result = new ArrayList<>(); // Process the queue until it becomes empty while (!queue.isEmpty()) { // Print the current number of requests in the queue result.add(queue.size()); // Process the first request (remove it at the next second) int firstRequestWaitTime = queue.poll(); // Fetch the first request // Decrease the waiting time of the remaining requests by 1 int size = queue.size(); for (int i = 0; i < size; i++) { int updatedWait = queue.poll() - 1; // Decrease wait time by 1 // If the updated wait time is still valid (i.e., > 0), put it back in the queue if (updatedWait > 0) { queue.offer(updatedWait); } } second++; // Move to the next second } result.add(0); return result; }