Back to blog
Oct 14, 2024
4 min read

Implement Queue using Stacks

Implement a FIFO queue using only two stacks with push, pop, peek, and empty operations.

Difficulty: Easy | Acceptance: 69.70% | Paid: No Topics: Stack, Design, Queue

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, peek, pop, 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 top, peek/pop from top, size, 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.

  • Examples

  • Constraints

  • Two Stacks - Amortized O(1)

  • Two Stacks - O(1) Push

Examples

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 push, pop, peek, and empty.
All the calls to pop and peek are valid.

Two Stacks - Amortized O(1)

Intuition Use two stacks where one acts as input and the other as output. Elements are transferred between stacks only when needed, making operations amortized O(1).

Steps

  • Maintain two stacks: inStack for push operations and outStack for pop/peek operations
  • When pushing, simply push to inStack
  • When popping or peeking, if outStack is empty, transfer all elements from inStack to outStack (this reverses the order)
  • Then pop or peek from outStack
  • Check if both stacks are empty for the empty operation
python
class MyQueue:
    def __init__(self):
        self.in_stack = []
        self.out_stack = []

    def push(self, x: int) -&gt; None:
        self.in_stack.append(x)

    def pop(self) -&gt; int:
        self._transfer()
        return self.out_stack.pop()

    def peek(self) -&gt; int:
        self._transfer()
        return self.out_stack[-1]

    def empty(self) -&gt; bool:
        return not self.in_stack and not self.out_stack

    def _transfer(self) -&gt; None:
        if not self.out_stack:
            while self.in_stack:
                self.out_stack.append(self.in_stack.pop())

Complexity

  • Time: Amortized O(1) for all operations. Each element is pushed and popped from each stack exactly once.
  • Space: O(n) where n is the number of elements in the queue
  • Notes: This is the optimal solution with amortized constant time complexity for all operations.

Two Stacks - O(1) Push

Intuition Always keep elements in the correct order by transferring elements during push operations, making push O(n) but pop and peek O(1).

Steps

  • Maintain two stacks: mainStack and tempStack
  • When pushing, transfer all elements from mainStack to tempStack, push the new element to mainStack, then transfer back from tempStack
  • When popping or peeking, simply pop or peek from mainStack
  • Check if mainStack is empty for the empty operation
python
class MyQueue:
    def __init__(self):
        self.main_stack = []
        self.temp_stack = []

    def push(self, x: int) -&gt; None:
        while self.main_stack:
            self.temp_stack.append(self.main_stack.pop())
        self.main_stack.append(x)
        while self.temp_stack:
            self.main_stack.append(self.temp_stack.pop())

    def pop(self) -&gt; int:
        return self.main_stack.pop()

    def peek(self) -&gt; int:
        return self.main_stack[-1]

    def empty(self) -&gt; bool:
        return not self.main_stack

Complexity

  • Time: O(n) for push, O(1) for pop, peek, and empty
  • Space: O(n) where n is the number of elements in the queue
  • Notes: This approach makes push expensive but pop and peek constant time. Useful when pop/peek operations are more frequent than push operations.