algoadvance

Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, pop, peek, and empty).

Implement the MyQueue class:

Notes:


Clarifying Questions

  1. Is the input size constrained?
    • Not necessarily. The main concern is ensuring the operations adhere strictly to the stack operations.
  2. Can we assume the inputs are valid?
    • Yes, assume that inputs given to each method are valid and within expected ranges.
  3. Should the solution be optimized for any specific operation?
    • The operations are evenly distributed; thus, our implementation should aim for overall efficiency in both push and pop operations.

Strategy

We’ll use two stacks to simulate the queue:

  1. Stack1 (in_stack): Used for enqueue operations.
  2. Stack2 (out_stack): Used for dequeue operations.

Operations:

This approach ensures that we always get the front element in O(1) average time, while pushes are O(1) and pops are amortized O(1) due to potential transfer between stacks.


Code

class MyQueue:

    def __init__(self):
        self.in_stack = []
        self.out_stack = []

    def push(self, x: int) -> None:
        self.in_stack.append(x)

    def pop(self) -> int:
        self._transfer()
        return self.out_stack.pop()

    def peek(self) -> int:
        self._transfer()
        return self.out_stack[-1]

    def empty(self) -> bool:
        return not self.in_stack and not self.out_stack
    
    def _transfer(self) -> None:
        if not self.out_stack:
            while self.in_stack:
                self.out_stack.append(self.in_stack.pop())

Time Complexity

This implementation efficiently simulates a queue using two stacks, ensuring all operations adhere to the required time complexities.

Try our interview co-pilot at AlgoAdvance.com