LeetCode #232 Easy

Implement Queue using Stacks

Implement Queue using Stacks is LeetCode 232 (Easy). Build MyQueue, a first-in-first-out queue, out of two stacks, using only stack operations (push to the top, peek or pop from the top, size, and is-empty):

  • push(x) adds x at the back; pop() removes and returns the front element.
  • peek() returns the front element; empty() says whether the queue has no elements.

Every pop and peek call is valid, so the queue is never empty when they run. The follow-up asks for amortized O(1) time per call.

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
stackqueuedesignamortized
Open on LeetCode ↗
02

Intuition

A stack hands back its newest element and a queue its oldest, so the order has to be flipped somewhere. Pouring one stack into another does exactly that: the bottom element of the first ends up on top of the second.

A queue using two stacks therefore keeps an in stack that takes every push and an out stack that serves every read. Pour only when out is empty. Everything already in out is older than anything in in, so it has to leave first; pouring early would bury it under newer elements.

How to spot this pattern

"Build a FIFO structure from LIFO parts" means reversing order, and two stacks reverse it in one pour. The pour-only-when-empty rule is what turns the follow-up's amortized O(1) from a hope into a guarantee.

03

Approach

Try it first

Before reading on, run push 1, push 2, pop, push 3, pop by hand with two stacks. After the first pop, decide whether 3 should be poured across before the second pop, and why.

1

Push onto the in stack

push(x) only appends x to in and never looks at out. The newest element belongs at the back of the queue, and the top of in is where the back lives until a pour moves it.

2

Before a read, refill out only if it is empty

In peek, if out is empty, pop every element off in and push it onto out. The oldest waiting element was at the bottom of in, so after the pour it is on top of out, ready to be read first.

3

Read the front from the top of out

peek returns the top of out, and pop calls peek and then removes that top. Routing pop through peek keeps the refill rule in one place, so the two methods cannot disagree about where the front is.

4

Report empty only when both stacks are

Elements can be waiting in either stack: new ones in in, poured ones in out. empty() returns true only if both are empty.

04

Code in Python, C++ and Java

▶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 front = self.peek()
▶11 self.out_stack.pop()
▶12 return front
▶13 
▶14 def peek(self) -> int:
▶15 if not self.out_stack:
▶16 while self.in_stack:
▶17 self.out_stack.append(self.in_stack.pop())
▶18 return self.out_stack[-1]
▶19 
▶20 def empty(self) -> bool:
▶21 return not self.in_stack and not self.out_stack
callinoutreturnedtwo empty stacks: in takes pushes, out serves reads
call
in[]
out[]
in will collect every pushed value. out will hold values in reversed order, oldest on top, ready to be read.
callpush 11intopoutreturnedpush 1: onto in, out is not touched
callpush 1
in[1]
out[]
1 is the newest element, so it goes on top of in. Push never looks at out, which keeps it a single stack operation.
callpush 212intopoutreturnedpush 2: onto in, out is not touched
callpush 2
in[1, 2]
out[]
2 is the newest element, so it goes on top of in. Push never looks at out, which keeps it a single stack operation.
callpeek1intop2outtopreturnedout is empty → pour: 2 moves to out
callpeek
in[1]
out[2]
out is empty, so every element in in is moved across. 2 comes off the top of in and goes on top of out. 1 left to move.
callpeekin21outtopreturnedkeep pouring: 1 moves to out
callpeek
in[]
out[2, 1]
1 comes off the top of in and goes on top of out. in is now empty, and the oldest element, 1, is on top of out.
callpeekin21outtopreturned1peek: top of out is 1 → return 1
callpeek
in[]
out[2, 1]
The top of out is the front of the queue, so peek returns 1 and leaves it in place.
callpopin21outtopreturned1out is not empty → no pour, its top is oldest
callpop
in[]
out[2, 1]
out is not empty. Its top, 1, is older than anything in in, so it must be removed first. Pouring now would bury it.
callpopin2outtopreturned11pop: take 1 off out → return 1
callpop
in[]
out[2]
1 was the oldest element in the queue. Pop removes it from the top of out and returns it.
callemptyin2outtopreturned11falseempty: in has 0, out has 1 → false
callempty
in[]
out[2]
The queue still holds 1 element, so the answer is false. Both stacks have to be checked, because elements can wait in either one.
callin2outtopreturned11falsereturned in order: 1, 1, false
returned[1, 1, false]
Every value left in the order it was pushed. Each one crossed from in to out exactly once, which is why the calls cost O(1) on average.
05

Reorder on every push

Keep the whole queue in main with the front element on top. To push x, move every element of main onto helper, push x onto the now-empty main so it sits at the bottom, then move everything back on top of it. Reads become a single stack call, but each push moves all stored elements twice.

▶1class MyQueue:
▶2 def __init__(self):
▶3 self.main = []
▶4 self.helper = []
▶5 
▶6 def push(self, x: int) -> None:
▶7 while self.main:
▶8 self.helper.append(self.main.pop())
▶9 self.main.append(x)
▶10 while self.helper:
▶11 self.main.append(self.helper.pop())
▶12 
▶13 def pop(self) -> int:
▶14 return self.main.pop()
▶15 
▶16 def peek(self) -> int:
▶17 return self.main[-1]
▶18 
▶19 def empty(self) -> bool:
▶20 return not self.main
06

Common pitfalls

Pouring while out still holds elements

✗ Wrong
while self.in_stack:
    self.out_stack.append(self.in_stack.pop())
✓ Right
if not self.out_stack:
    while self.in_stack:
        self.out_stack.append(self.in_stack.pop())

Newer elements land on top of older ones. Push 1, push 2, pop returns 1 and leaves 2 in out; then push 3 and pop pours 3 on top of 2 and returns 3, when the front of the queue is 2.

Checking only one stack in empty()

✗ Wrong
def empty(self) -> bool:
    return not self.out_stack
✓ Right
def empty(self) -> bool:
    return not self.in_stack and not self.out_stack

Pushed elements sit in in until a read pours them. After a single push 1, out is still empty, so this returns true for a queue holding one element.

07

Complexity

Time
O(1) amortized
Space
O(n)
Each element is pushed onto in, popped from in, pushed onto out and popped from out: four stack operations over its whole life. So n calls cost O(n) in total, even though a single peek that triggers a pour can take O(n). The two stacks together hold the n stored elements.
08

Implement Queue using Stacks FAQ

Can a queue be built from a single stack?

Yes, if recursion is allowed. To pop, take the top element off, recurse until the stack holds one element (the oldest), remove and return it, then push the other elements back as the calls return. The call stack plays the role of the second stack, and each pop costs O(n).

Why is there no amortized trick for a stack built from queues?

Moving elements from one queue to another keeps their order, so a single transfer cannot flip it for many later reads. In Implement Stack using Queues either push or pop pays O(n) on every call.

Where is the array-based queue covered?

Implement Queue using Arrays builds a fixed-size queue on one array that wraps around, with every operation O(1) in the worst case rather than on average.