The Implement Stack using Queues coding problem asks you to simulate a Last-In-First-Out (LIFO) stack using only one or two standard First-In-First-Out (FIFO) queues. You must implement push, pop, top, and empty using only the standard queue operations (push, peek, pop, size).
Similar to its counterpart (Queue using Stacks), this problem is a classic at companies like Amazon and Adobe to evaluate a candidate's flexible thinking regarding data flow. It tests your ability to manipulate a data structure to behave in a way that is inherently contrary to its design. It also tests your ability to analyze the time complexity of operations when one data structure must "emulate" another.
There are two common strategies:
Queue 1, first add it to Queue 2, then move all elements from Queue 1 to Queue 2, and finally swap the names of the two queues. This ensures the newest element is always at the front of Queue 1.size - 1 times, remove the front element and re-add it to the back. This "rotates" the queue until the newest element is at the front.Using the One Queue approach:
push(1): Queue = [1].push(2):
[1, 2].[2, 1].push(3):
[2, 1, 3].[1, 3, 2].[3, 2, 1].
Now pop() or top() will correctly return 3, the last element pushed.pop instead of push. While both are valid, the interviewer often asks for one specifically. Making pop requires transferring all but one element between queues for every call.Be ready to discuss the Time vs. Space trade-off. Using one queue saves space but requires more careful "rotation" logic. Using two queues is often more intuitive but doubles the memory footprint.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Implement Queue using Stacks | Easy | Solve | |
| Min Stack | Medium | Solve | |
| Number of Recent Calls | Easy | Solve | |
| Flatten Nested List Iterator | Medium | Solve | |
| Design a Stack With Increment Operation | Medium | Solve |