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)addsxat 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.
- 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
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.
"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.
Approach
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.
Two ways to keep the order
Push to in; refill out from in only when a read finds out empty.
- Meets the follow-up: each element crosses once.
- Cheap push: always a single stack push.
Keep one stack with the front on top by moving everything aside and back for each push.
- Simple reads: pop and peek are one stack call.
- Slow writes: every push moves all elements twice.
Both use two stacks. The steps, code and live demo pour lazily; the version that reorders on every push follows the demo.
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.
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.
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.
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.
Code in Python, C++ and Java
in will collect every pushed value. out will hold values in reversed order, oldest on top, ready to be read.in. Push never looks at out, which keeps it a single stack operation.in. Push never looks at out, which keeps it a single stack operation.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.in and goes on top of out. in is now empty, and the oldest element, 1, is on top of out.out is the front of the queue, so peek returns 1 and leaves it in place.out is not empty. Its top, 1, is older than anything in in, so it must be removed first. Pouring now would bury it.out and returns it.in to out exactly once, which is why the calls cost O(1) on average.in will collect every pushed value. out will hold values in reversed order, oldest on top, ready to be read.in. Push never looks at out, which keeps it a single stack operation.in. Push never looks at out, which keeps it a single stack operation.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.in and goes on top of out. in is now empty, and the oldest element, 1, is on top of out.out and returns it.in. Push never looks at out, which keeps it a single stack operation.out is not empty. Its top, 2, is older than anything in in (3), so it must be removed first. Pouring now would bury it.out and returns it.out is empty, so every element in in is moved across. 3 comes off the top of in and goes on top of out. in is now empty, and the oldest element, 3, is on top of out.out and returns it.in to out exactly once, which is why the calls cost O(1) on average.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.
Common pitfalls
Pouring while out still holds elements
while self.in_stack:
self.out_stack.append(self.in_stack.pop())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()
def empty(self) -> bool:
return not self.out_stackdef empty(self) -> bool:
return not self.in_stack and not self.out_stackPushed 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.
Complexity
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.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.