Revolving Door - Amazon Top Interview Questions


Problem Statement :


You are given a list of list of integers requests. requests[i] contains [time, direction] meaning at time time, a person arrived at the door and either wanted to go in (1) or go out (0).

Given that there's only one door and it takes one time unit to use the door, we have the following rules to resolve conflicts:

The door starts with in position and then is set to the position used by the last person.
If there's only one person at the door at given time, they can use the door.
When two or more people want to go in, earliest person goes first and then the direction previously used holds precedence.
If no one uses the door for one time unit, it reverts back to the starting in position.
Return a sorted list of lists where each element contains [time, direction], meaning at time, a person either went in or out.

Constraints

0 ≤ n ≤ 100,000 where n is the length of requests

Example 1

Input

requests = [
    [1, 0],
    [2, 1],
    [5, 0],
    [5, 1],
    [2, 0]
]

Output

[
    [1, 0],
    [2, 0],
    [3, 1],
    [5, 1],
    [6, 0]
]

Explanation

The door starts as in

At time 1, there's only one person so they can go out. Door becomes out.

At time 2, there's two people but the person going out has priority so they go out.

At time 3, the person looking to go in can now go in.

At time 5, there's two people but the person going in has priority so they go out.

At time 6, the last person can go out.

Example 2

Input

requests = [
    [1, 0],
    [2, 0],
    [2, 1],
    [1, 1]
]

Output

[
    [1, 1],
    [2, 0],
    [3, 0],
    [4, 1]
]

Explanation

The door starts as in

At time 1, there's two people but the person going in has higher priority.

At time 2, the other person who came at time 1 can go out. Door becomes out

At time 3, there's two people but the person going out has higher priority.

At time 4, the last person can go in



Solution :



title-img




                        Solution in C++ :

vector<vector<int>> solve(vector<vector<int>> &requests) {
    int n = requests.size();
    vector<vector<int>> finalState;

    sort(requests.begin(), requests.end(),
         [&](vector<int> &v1, vector<int> &v2) { return v1[0] < v2[0]; });

    int gateDirection = 1;
    int time = -1;

    vector<vector<int>> currentRequests;

    int left = 0;
    int right = 0;

    while (right < n) {
        if (requests[left][0] - time >= 1) gateDirection = 1;
        if (time < requests[left][0]) time = requests[left][0];
        while (right < n && requests[right][0] == requests[left][0]) {
            currentRequests.push_back(requests[right]);
            right++;
        }

        while (!currentRequests.empty()) {
            sort(currentRequests.begin(), currentRequests.end(),
                 [&](vector<int> &v1, vector<int> &v2) {
                     if (v1[0] == v2[0]) {
                         if (gateDirection == v1[1])
                             return false;
                         else if (gateDirection == v2[1])
                             return true;
                     }
                     return v1[0] > v2[0];
                 });

            finalState.push_back({time, currentRequests.back()[1]});
            gateDirection = currentRequests.back()[1];
            currentRequests.pop_back();
            time++;
        }

        left = right;
    }
    return finalState;
}
                    


                        Solution in Java :

import java.util.*;

class Solution {
    public int[][] solve(int[][] requests) {
        // Create and populate Queues for in- and out-going times
        PriorityQueue<Integer> inQueue = new PriorityQueue<>();
        PriorityQueue<Integer> outQueue = new PriorityQueue<>();
        for (int i = requests.length - 1; i >= 0; i--) {
            if (requests[i][1] == 0) {
                outQueue.add(requests[i][0]);
            } else {
                inQueue.add(requests[i][0]);
            }
        }

        // Build result array
        int[][] result = new int[requests.length][2];
        int time = -1;
        int door = 1;
        for (int i = 0; i < requests.length; i++) {
            // inQueue empty or outQueue item smaller
            if (inQueue.size() == 0 || outQueue.size() != 0 && outQueue.peek() < inQueue.peek()) {
                time = Math.max(time + 1, outQueue.poll());
                result[i] = new int[] {time, 0};
                door = 0;
            }
            // outQueue empty or inQueue item smaller
            else if (outQueue.size() == 0 || inQueue.peek() < outQueue.peek()) {
                time = Math.max(time + 1, inQueue.poll());
                result[i] = new int[] {time, 1};
                door = 1;
            }
            // equal items in both queues
            else {
                if (inQueue.peek() - time > 1) {
                    door = 1;
                }
                if (door == 1) {
                    time = Math.max(time + 1, inQueue.poll());
                    result[i] = new int[] {time, 1};
                } else {
                    time = Math.max(time + 1, outQueue.poll());
                    result[i] = new int[] {time, 0};
                }
            }
        }
        return result;
    }
}
                    


                        Solution in Python : 
                            
class Solution:
    def solve(self, requests):
        requests.sort()
        i, j = 0, 1
        while i < len(requests):
            if j < len(requests) and requests[i][0] == requests[j][0]:
                j += 1
                continue

            if not i or requests[i][0] - requests[i - 1][0] > 1:
                prev_direc = 1
            else:
                prev_direc = requests[i - 1][1]

            requests[i:j] = sorted(requests[i:j], reverse=prev_direc)

            if i and requests[i][0] <= requests[i - 1][0]:
                requests[i][0] = requests[i - 1][0] + 1
            for k in range(i + 1, j):
                requests[k][0] = requests[k - 1][0] + 1

            i = j
            j = i + 1

        return requests
                    


View More Similar Problems

Sparse Arrays

There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results. Example: strings=['ab', 'ab', 'abc'] queries=['ab', 'abc', 'bc'] There are instances of 'ab', 1 of 'abc' and 0 of 'bc'. For each query, add an element to the return array, results=[2,1,0]. Fun

View Solution →

Array Manipulation

Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array. Example: n=10 queries=[[1,5,3], [4,8,7], [6,9,1]] Queries are interpreted as follows: a b k 1 5 3 4 8 7 6 9 1 Add the valu

View Solution →

Print the Elements of a Linked List

This is an to practice traversing a linked list. Given a pointer to the head node of a linked list, print each node's data element, one per line. If the head pointer is null (indicating the list is empty), there is nothing to print. Function Description: Complete the printLinkedList function in the editor below. printLinkedList has the following parameter(s): 1.SinglyLinkedListNode

View Solution →

Insert a Node at the Tail of a Linked List

You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty. Input Format: You have to complete the SinglyLink

View Solution →

Insert a Node at the head of a Linked List

Given a pointer to the head of a linked list, insert a new node before the head. The next value in the new node should point to head and the data value should be replaced with a given value. Return a reference to the new head of the list. The head pointer given may be null meaning that the initial list is empty. Function Description: Complete the function insertNodeAtHead in the editor below

View Solution →

Insert a node at a specific position in a linked list

Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is e

View Solution →