Implement Queue using Stacks

Easy

Topics
StackQueueDesign

Implement a first-in-first-out (FIFO) queue using only two stacks. Implement MyQueue with push(x), pop() (removes and returns the front element), peek() (returns the front element), and empty().

Example 1

returnsMyQueue()push(1)push(2)peek()1pop()1empty()false
The visible behaviour must be a queue — oldest element out first — while the only storage permitted is stacks, which give the newest back first. Every operation has to answer exactly as a real queue would.
Calls run top to bottom; the arrow shows what each one returns.
Input:  operations = ["MyQueue","push","push","peek","pop","empty"], values = [[],[1],[2],[],[],[]]
Output: [null,null,null,1,1,false]

Constraints

  • 1 <= x <= 9
  • At most 100 calls to push, pop, peek, and empty.
  • pop and peek are only called on a non-empty queue.
Editorial — intuition, approach, complexity and pitfalls

Intuition

A stack is LIFO but a queue is FIFO. Use an input stack for pushes and an output stack for pops. When the output stack is empty, pour the input stack into it — this reverses the order so the oldest element ends up on top.

Approach

  1. push always goes onto the input stack.
  2. For pop/peek, if the output stack is empty, move every element from input to output (reversing order).
  3. The front of the queue is then the top of the output stack.

Dry Run

MyQueue()
  push 1   -> null     inp [1]       out []
  push 3   -> null     inp [1, 3]    out []
  pop      -> 1        inp []        out [3]    out was empty, so pour: 3 lands
                                                first, then 1 on top; pop takes 1
  peek     -> 3        inp []        out [3]    out is not empty, no pour
  push 1   -> null     inp [1]       out [3]    the new 1 waits in inp
  pop      -> 3        inp [1]       out []     out still held the 3, no pour
  pop      -> 1        inp []        out []     out empty, pour the 1 across
  push 3   -> null     inp [3]       out []
  empty    -> false    inp [3]       out []
  pop      -> 3        inp []        out []
  push 8   -> null     inp [8]       out []
  empty    -> false    inp [8]       out []
answer null|null|null|1|3|null|3|1|null|false|3|null|false
The "push 1" on row 5 is the row that justifies the only-when-empty rule. At that
instant out holds [3] and inp holds [1]. The 3 is older and has to leave first;
pouring inp across right then would stack the newer 1 on top of it and the next
pop would wrongly return 1. Waiting until out drains keeps the two halves ordered
without ever recording arrival times.
Each element crosses from inp to out exactly once in its life, which is where the
amortized O(1) comes from. The one expensive pop that pours k elements has already
been paid for by the k pushes that put them there.

Complexity

  • Time — O(1) amortized: each element is moved between stacks at most once.
  • Space — O(n): the two stacks hold all queued elements.

Common Pitfalls

  • Only refill the output stack when it is empty; refilling early scrambles the order.

Full Solution — all languages

class MyQueue:
    def __init__(self):
        self.inp = []
        self.out = []
    def push(self, x):
        self.inp.append(x)
    def _shift(self):
        if not self.out:
            while self.inp:
                self.out.append(self.inp.pop())
    def pop(self):
        self._shift()
        return self.out.pop()
    def peek(self):
        self._shift()
        return self.out[-1]
    def empty(self):
        return not self.inp and not self.out
Asked at Qualcomm
SensAI
Beta
Tap the mic to stop voice mode