How to Implement a Queue using Stacks
A step-by-step guide on how to simulate Queue behavior using two Stacks to achieve efficient enqueue and dequeue operations.
Understand the Problem
A Queue follows First In First Out order but a Stack follows Last In First Out order. These are opposites. The trick is to use two stacks together in a way that reverses the order and simulates queue behavior.
Set Up Two Stacks
Create two stacks. Call the first one the Input Stack and the second one the Output Stack. All new elements go into the Input Stack during enqueue. All elements come out of the Output Stack during dequeue.
Implement Enqueue
The enqueue operation is simple. Just push the new element onto the Input Stack. No movement between stacks happens during enqueue. This is always a constant time operation.
Implement Dequeue
When dequeue is called, first check if the Output Stack is empty. If it is not empty, simply pop from the Output Stack and return the value. If it is empty, transfer all elements from the Input Stack to the Output Stack one by one by popping from Input and pushing to Output.
Understand Why Transfer Works
When you pop all elements from the Input Stack and push them onto the Output Stack, the order gets reversed. The element that was pushed first into Input Stack ends up on top of Output Stack, which is exactly the First In First Out behavior a queue requires.
Implement Peek
Peek works the same way as dequeue but without removing the element. If the Output Stack is not empty, peek at its top. If it is empty, transfer all elements from Input to Output first, then peek at the top of Output Stack.
Analyze the Time Complexity
Each element is moved from Input Stack to Output Stack at most once in its entire lifetime. So even though a single dequeue might trigger a transfer, the amortized cost per operation across many operations is constant time. This is called amortized constant time complexity.
Ready to master this completely?
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

