Implement Stack using Two Queues
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
Implementing a stack with two queues is a classic interview and data-structure exercise. It forces you to simulate Last-In First-Out behavior on top of First-In First-Out primitives. The core design choice is where you pay the cost: during push or during pop.
Problem Setup and Tradeoff
A stack requires these operations:
push(x)inserts an element on top.pop()removes and returns the top element.top()returns the top element without removing it.empty()tells whether the stack has no elements.
With two queues, there are two standard strategies:
- expensive
push, cheappop - cheap
push, expensivepop
Both are valid. Choose based on expected call frequency.
Strategy A: Expensive Push, Cheap Pop
In this approach, queue q1 always keeps stack order at its front. To push, place the new element into q2, move all items from q1 to q2, then swap the two queues.
Python implementation
Complexity for Strategy A:
push:O(n)pop:O(1)top:O(1)- extra space:
O(n)
This is a good choice when reads and pops are frequent compared to pushes.
Strategy B: Cheap Push, Expensive Pop
You can invert the cost profile. Push directly to q1, then for pop move n - 1 elements to q2, remove the last element, and swap queues.
Complexity for Strategy B:
push:O(1)pop:O(n)top:O(n)- extra space:
O(n)
Correctness Intuition
For Strategy A, every push rebuilds queue order so the newest element becomes the next dequeued item from q1. That exactly matches stack top behavior.
For Strategy B, queue order remains insertion order until pop time. The transfer step isolates the newest element as the final remaining element in q1, which is then removed.
A short invariant for Strategy A is:
- after each
push,q1front equals stack top.
A short invariant for Strategy B is:
- before each
pop, newest element is the last item inq1.
These invariants make debugging easier than memorizing raw steps.
Testing Recommendations
For interview code, basic manual checks are often enough. For production helpers, add unit tests for:
- popping from empty stack
- top on empty stack
- alternating push and pop sequences
- repeated pushes followed by full drain
Example using Python assertions:
Common Pitfalls
A common bug is forgetting to swap queues after transfer. Without swapping, subsequent calls read from the wrong queue and order breaks.
Another issue is not handling empty states. pop and top should fail explicitly instead of returning incorrect sentinel values.
Developers also mix strategy logic accidentally, such as using Strategy A push with Strategy B top. Keep one consistent method set.
Finally, avoid hiding complexity assumptions. If your workload is push-heavy, Strategy A may degrade throughput. Pick the strategy that aligns with expected usage patterns.
Summary
- Two queues can implement stack semantics correctly with clear invariants.
- Strategy A makes
pushexpensive andpopcheap. - Strategy B makes
pushcheap andpopexpensive. - Queue swapping and empty checks are critical for correctness.
- Unit tests should cover edge cases and operation order guarantees.
Related reading
- Implementation consistent replica in peer-to-peer application
- Implementation of a hits in last second/minute/hour data structure
- Implementation of C lower_bound
- Implementation of distributed greedy algorithm for finding maximum independent set
- Implementation of delayed queue for PHP AMQP
- Implementations of image matching using Scalable Recognition with a Vocabulary Tree
- Implementation of locality-sensitive hashing with min-hash
- Implementation of Logistic regression with Gradient Descent in Java

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.