Implement Queue using Stacks (LeetCode 232): Solution and Explanation
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
- Keep two stacks:
in_stackfor incoming values andout_stackfor values ready to leave. push(x): pushxontoin_stack.peek(): ifout_stackis empty, pop every value fromin_stackand push it ontoout_stack. Then return the top ofout_stack.pop(): callpeek()so the front is on top ofout_stack, then pop and return that top.empty(): return true only when both stacks are empty.
Step-by-step example
commands = ["MyQueue","push","push","peek","pop","empty"], values = [[],[1],[2],[],[],[]]
MyQueue()creates two empty stacks. Output so far: [null].push(1)puts 1 onin, soin= [1].push(2)puts 2 on top, soin= [1, 2]. Output: [null, null, null].peek()findsoutempty, so it pours: 2 moves first, then 1. Nowin= [] andout= [2, 1] with 1 on top. It returns 1.pop()seesoutis not empty, so no pouring is needed. It pops 1 and returns it, leavingout= [2].empty()returns false because 2 is still inout. 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_stack1class MyQueue {
2 private Deque<Integer> inStack;
3 private Deque<Integer> outStack;
4
5 public MyQueue() {
6 inStack = new ArrayDeque<>();
7 outStack = new ArrayDeque<>();
8 }
9
10 public void push(int x) {
11 inStack.push(x);
12 }
13
14 public int pop() {
15 peek();
16 return outStack.pop();
17 }
18
19 public int peek() {
20 if (outStack.isEmpty()) {
21 while (!inStack.isEmpty()) {
22 outStack.push(inStack.pop());
23 }
24 }
25 return outStack.peek();
26 }
27
28 public boolean empty() {
29 return inStack.isEmpty() && outStack.isEmpty();
30 }
31}1class MyQueue {
2 stack<int> inStack;
3 stack<int> outStack;
4public:
5 MyQueue() {
6 inStack = stack<int>();
7 }
8
9 void push(int x) {
10 inStack.push(x);
11 }
12
13 int pop() {
14 int front = peek();
15 outStack.pop();
16 return front;
17 }
18
19 int peek() {
20 if (outStack.empty()) {
21 while (!inStack.empty()) {
22 outStack.push(inStack.top());
23 inStack.pop();
24 }
25 }
26 return outStack.top();
27 }
28
29 bool empty() {
30 return inStack.empty() && outStack.empty();
31 }
32};Time and space complexity
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.
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
inontooutwhileoutstill has values. The newer values land on top of older ones and the queue order breaks. - Moving values back from
outtoinafter each pop. It is never needed and turns every operation into O(n). - Checking only
in_stack(or onlyout_stack) inempty(). Values can be sitting in either stack. - Duplicating the transfer logic in both
popandpeekand letting the copies drift apart. Havingpopcallpeekkeeps 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.