Middle Operable Deque - Amazon Top Interview Questions


Problem Statement :


Implement a data structure with the following methods:

void appendLeft(int val) when appends val to the left of the deque.

int popLeft() which pops the leftmost value of the deque. If it's empty, return -1.

void append(int val) when appends val to the end of the deque.

int pop() which pops the last value of the deque. If it's empty, return -1.

void appendMiddle(int val) when appends val to the middle of the deque.

int popMiddle() which pops the middle value of the deque. If it's empty, return -1.

Middle is defined to be floor(k / 2) where k is the length of the deque.

Constraints

0 ≤ n ≤ 100,000 where n is the number of calls to any method.

Example 1

Input

methods = ["constructor", "append", "appendLeft", "appendMiddle", "appendLeft", "popMiddle", "pop", "popLeft"]
arguments = [[], [1], [3], [2], [0], [], [], []]`

Output

[None, None, None, None, None, 3, 1, 0]



Solution :



title-img




                        Solution in C++ :

class MiddleOperableDeque {
    deque<int> q1, q2;

    public:
    MiddleOperableDeque() {
    }

    void appendLeft(int val) {
        q1.push_front(val);
        if (q1.size() > q2.size() + 1) q2.push_front(q1.back()), q1.pop_back();
    }

    int popLeft() {
        if (q1.empty()) return -1;
        int ret = q1.front();
        q1.pop_front();
        if (q1.size() < q2.size()) q1.push_back(q2.front()), q2.pop_front();
        return ret;
    }

    void append(int val) {
        q2.push_back(val);
        if (q1.size() < q2.size()) q1.push_back(q2.front()), q2.pop_front();
    }

    int pop() {
        if (q2.empty()) {
            if (q1.empty()) return -1;
            int ret = q1.back();
            q1.pop_back();
            return ret;
        }
        int ret = q2.back();
        q2.pop_back();
        if (q1.size() > q2.size() + 1) q2.push_front(q1.back()), q1.pop_back();
        return ret;
    }

    void appendMiddle(int val) {
        if (q1.size() == q2.size())
            q1.push_back(val);
        else
            q2.push_front(q1.back()), q1.back() = val;
    }

    int popMiddle() {
        if (q1.empty()) return -1;
        int ret = q1.back();
        q1.pop_back();
        if (q1.size() < q2.size()) q1.push_back(q2.front()), q2.pop_front();
        return ret;
    }
};
                    




                        Solution in Python : 
                            
class MiddleOperableDeque:
    def __init__(self):
        # Represent the queue as the concatenation of two deques.
        # We will make sure the gap between the deques corresponds to the "middle".
        self.left = deque()
        self.right = deque()

    def _rebalance(self):
        # Ensure that len(self.left) == floor(n / 2) and len(self.right) == ceil(n / 2)
        if len(self.left) > len(self.right):
            self.right.appendleft(self.left.pop())
        elif len(self.right) > len(self.left) + 1:
            self.left.append(self.right.popleft())

    def appendLeft(self, val):
        self.left.appendleft(val)
        self._rebalance()

    def popLeft(self):
        if self.left:
            val = self.left.popleft()
        elif self.right:
            # Special case: When there is only one element, it's in `self.right`
            val = self.right.popleft()
        else:
            return -1
        self._rebalance()
        return val

    def append(self, val):
        self.right.append(val)
        self._rebalance()

    def pop(self):
        if self.right:
            val = self.right.pop()
        else:
            # No special case - if self.right is empty then the whole queue is empty
            return -1
        self._rebalance()
        return val

    def appendMiddle(self, val):
        # If the overall length is odd, tiebreak by putting the element to the left of the middle element
        self.left.append(val)
        self._rebalance()

    def popMiddle(self):
        if not self.left and not self.right:
            return -1
        elif len(self.left) == len(self.right):
            # If the overall length is even, tiebreak by taking the element on the left
            val = self.left.pop()
        else:
            val = self.right.popleft()
        self._rebalance()
        return val
                    


View More Similar Problems

Poisonous Plants

There are a number of plants in a garden. Each of the plants has been treated with some amount of pesticide. After each day, if any plant has more pesticide than the plant on its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each of the plants. Determine the number of days after which no plant dies, i.e. the time after which there is no plan

View Solution →

AND xor OR

Given an array of distinct elements. Let and be the smallest and the next smallest element in the interval where . . where , are the bitwise operators , and respectively. Your task is to find the maximum possible value of . Input Format First line contains integer N. Second line contains N integers, representing elements of the array A[] . Output Format Print the value

View Solution →

Waiter

You are a waiter at a party. There is a pile of numbered plates. Create an empty answers array. At each iteration, i, remove each plate from the top of the stack in order. Determine if the number on the plate is evenly divisible ith the prime number. If it is, stack it in pile Bi. Otherwise, stack it in stack Ai. Store the values Bi in from top to bottom in answers. In the next iteration, do the

View Solution →

Queue using Two Stacks

A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed. A basic que

View Solution →

Castle on the Grid

You are given a square grid with some cells open (.) and some blocked (X). Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell. Given a grid, a start and a goal, determine the minmum number of moves to get to the goal. Function Description Complete the minimumMoves function in the editor. minimumMoves has the following parameter(s):

View Solution →

Down to Zero II

You are given Q queries. Each query consists of a single number N. You can perform any of the 2 operations N on in each move: 1: If we take 2 integers a and b where , N = a * b , then we can change N = max( a, b ) 2: Decrease the value of N by 1. Determine the minimum number of moves required to reduce the value of N to 0. Input Format The first line contains the integer Q.

View Solution →