Implement Queue using Stacks
Master this topic with zero to advance depth.
Implement Queue using Stacks
Implement a first in first out (FIFO) queue using only two his stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).
Examples
Level I: Two Stacks (Push O(N))
Intuition
To make a stack behave like a queue, the oldest entered elements must be kept at the top of the stack. For every newly pushed element, we can move all elements to a temporary stack, push the new element to the bottom, and move everything back.
Level II: Recursive (One Stack)
Intuition
We can implement the 'pop' or 'peek' operation using a single stack and recursion. The function call stack acts as the second stack. To pop the bottom element, we pop the top, recurse to the bottom, and then push the popped element back as we return. This is less efficient than two stacks but insightful.
Level III: Amortized O(1) with Two Stacks
Use an input stack to handle pushes and an output stack for peeks/pops. When the output stack is empty, transfer all elements from input to output. This reverses the order to FIFO.
Detailed Dry Run
| Operation | Value | in_stack | out_stack | Output |
|---|---|---|---|---|
| push | 1 | [1] | [] | - |
| push | 2 | [1, 2] | [] | - |
| peek | - | [] | [2, 1] | 1 |
| pop | - | [] | [2] | 1 |
| empty | - | [] | [2] | false |
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.