Implement Queue using Stacks (LeetCode 232): Solution and Explanation

Easy
Stack
Design
Queue

Build a first-in-first-out queue with push, pop, peek and empty, but the only storage you may use is stacks, and you can only touch their tops. The goal is for every operation to cost O(1) amortized.

Intuition

A stack hands values back in the reverse of the order they arrived, and a queue hands them back in the same order. The fix is to reverse twice. If you pop every value off one stack and push it onto a second stack, the oldest value, which was buried at the bottom, ends up on top of the second stack.

That suggests two roles. The in stack accepts every new value, so push is a single stack push. The out stack holds values in serving order, so its top is always the front of the queue, and pop and peek just read its top.

The subtle part is when to move values across. If out still has values, they are all older than anything in in, so pouring in on top of them would bury the real front. You only pour when out is empty, and then you pour everything at once.

A single pop can be slow when it triggers a pour of n values. But every value is pushed onto in once, moved to out once, and popped from out once. Over any sequence of n operations that is at most 3n stack operations, so the average cost per call is constant.

Approach: Two stacks with lazy transfer

  1. Keep two stacks: in_stack for incoming values and out_stack for values ready to leave.
  2. push(x): push x onto in_stack.
  3. peek(): if out_stack is empty, pop every value from in_stack and push it onto out_stack. Then return the top of out_stack.
  4. pop(): call peek() so the front is on top of out_stack, then pop and return that top.
  5. empty(): return true only when both stacks are empty.

Step-by-step example

commands = ["MyQueue","push","push","peek","pop","empty"], values = [[],[1],[2],[],[],[]]
  1. MyQueue() creates two empty stacks. Output so far: [null].
  2. push(1) puts 1 on in, so in = [1]. push(2) puts 2 on top, so in = [1, 2]. Output: [null, null, null].
  3. peek() finds out empty, so it pours: 2 moves first, then 1. Now in = [] and out = [2, 1] with 1 on top. It returns 1.
  4. pop() sees out is not empty, so no pouring is needed. It pops 1 and returns it, leaving out = [2].
  5. empty() returns false because 2 is still in out. The final output is [null,null,null,1,1,false].

Code: Python, Java, C++

1class MyQueue:
2    def __init__(self):
3        self.in_stack = []
4        self.out_stack = []
5
6    def push(self, x: int) -> None:
7        self.in_stack.append(x)
8
9    def pop(self) -> int:
10        self.peek()
11        return self.out_stack.pop()
12
13    def peek(self) -> int:
14        if not self.out_stack:
15            while self.in_stack:
16                self.out_stack.append(self.in_stack.pop())
17        return self.out_stack[-1]
18
19    def empty(self) -> bool:
20        return not self.in_stack and not self.out_stack
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(1) amortized

push and empty are always O(1). pop and peek are O(1) unless they trigger a pour, and each value is poured at most once in its lifetime, so n operations cost O(n) in total.

Space

O(n)

Each value currently in the queue lives in exactly one of the two stacks, so storage grows with the number of stored values.

Other approaches

Costly push (time O(n) push, O(1) pop, space O(n))

Keep the stack ordered with the front on top at all times. On every push, move everything to a helper stack, push the new value, and move everything back. pop and peek become O(1), but each push is O(n) every time, not just occasionally.

Pour on every pop (time O(1) push, O(n) pop, space O(n))

Keep all values in one stack and, on each pop, move them to a second stack, pop the top, and move them back. It is correct and easy to reason about, but every pop costs O(n), so a long sequence becomes quadratic.

Common mistakes

  • Pouring in onto out while out still has values. The newer values land on top of older ones and the queue order breaks.
  • Moving values back from out to in after each pop. It is never needed and turns every operation into O(n).
  • Checking only in_stack (or only out_stack) in empty(). Values can be sitting in either stack.
  • Duplicating the transfer logic in both pop and peek and letting the copies drift apart. Having pop call peek keeps one source of truth.

Frequently asked questions

Why is a single pop O(n) in the worst case but the overall cost still O(1) amortized?

A pop that finds out empty may move every stored value, which is O(n) for that call. Each value can only be moved once, though, so the total number of moves over n operations is at most n. Spread across the calls, that is a constant amount of work per operation.

Why must out be empty before moving values over?

Everything in out arrived before everything in in. If you pour while out still holds values, the newer values from in end up on top and would be returned before the older ones, which breaks first-in-first-out order.

Can I use a deque or list instead of a stack?

Yes, as long as you only use stack operations on it: push to the end, pop from the end, look at the end, check size. Python lists and Java's ArrayDeque used this way count as stacks.

What is the time complexity of Implement Queue using Stacks?

With two stacks and lazy transfer, push and empty are O(1), and pop and peek are O(1) amortized. Space is O(n) for the stored values.