LeetCode Link: 232. Implement Queue using Stacks

Problem Definition

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

Implement the MyQueue class:

  • void push(int x) Pushes element x to the back of the queue.
  • int pop() Removes the element from the front of the queue and returns it.
  • int peek() Returns the element at the front of the queue.
  • boolean empty() Returns true if the queue is empty, false otherwise.

Notes:

  • You must use only standard operations of a stack, which means only push to toppeek/pop from topsize, and is empty operations are valid.
  • Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.

Example 1:

Input:

["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]

Output:

[null, null, null, 1, 1, false]

Explanation:

MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

Constraints:

  • 1 <= x <= 9
  • At most 100 calls will be made to pushpoppeek, and empty.
  • All the calls to pop and peek are valid.

Understanding the Challenge

The key challenge here lies in the fundamental difference between stacks and queues:

  • A stack follows LIFO (Last In, First Out)
  • A queue follows FIFO (First In, First Out)

To bridge this gap, we'll need to use two stacks: an input stack and an output stack. The interaction between these two stacks will help us achieve the FIFO behavior of a queue.

How It Works

Let's break down the key operations:

  1. Push Operation
    • New elements are always pushed to the input stack
    • This maintains the order of insertion
  2. Pop Operation
    • If the output stack has elements, we pop from there
    • If the output stack is empty, we transfer all elements from the input stack to the output stack
    • This transfer reverses the order, effectively converting LIFO to FIFO
  3. Peek Operation
    • Similar to pop, but we return the top element without removing it
    • Uses the same transfer mechanism when necessary

Below is a CodeSandbox I created to illustrate:

Solution

class MyQueue:
    def __init__(self):
        """
        Initialize two stacks:
        - stack_in: handles push operations
        - stack_out: handles pop operations
        """
        self.stack_in = []   # Input stack
        self.stack_out = []  # Output stack

    def push(self, x: int) -> None:
        """
        Simply push new elements to the input stack
        Time complexity: O(1)
        """
        self.stack_in.append(x)

    def pop(self) -> int:
        """
        Pop the front element from the queue
        Time complexity: Amortized O(1)
        """
        # Handle empty queue case
        if self.empty():
            return None
        
        # If output stack has elements, pop from there
        if self.stack_out:
            return self.stack_out.pop()
        
        # If output stack is empty, transfer all elements from input stack
        while self.stack_in:
            self.stack_out.append(self.stack_in.pop())
        return self.stack_out.pop()

    def peek(self) -> int:
        """
        Return the front element without removing it
        Time complexity: Amortized O(1)
        """
        if self.empty():
            return None
        
        if not self.stack_out:
            while self.stack_in:
                self.stack_out.append(self.stack_in.pop())
        return self.stack_out[-1]

    def empty(self) -> bool:
        """
        Check if the queue is empty
        Time complexity: O(1)
        """
        return len(self.stack_in) == 0 and len(self.stack_out) == 0

Conclusion

This problem demonstrates how to simulate a queue using stacks. It emphasizes problem-solving with constrained resources and showcases techniques for efficient code reuse. The Python implementation is intuitive and leverages helper functions for better clarity and maintainability.