Implement Stack using Queues
Master this topic with zero to advance depth.
Implement Stack using Queues
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty).
Examples
Level I: Two Queues (Push O(N))
Intuition
When a new element arrives, enqueue it to a secondary empty queue. Then, dequeue all elements from the main queue and enqueue them after the new element. Finally, swap the main and secondary queues. The newest element is now at the front.
Level III: One Queue (Optimize Space)
When pushing an element, add it to the queue, and then rotate the queue (pop and re-add) N-1 times so the newly added element is now at the front. This avoids needing a second queue temporarily.
Detailed Dry Run
| Operation | Value | Queue State | Action |
|---|---|---|---|
| push | 1 | [1] | Add 1 |
| push | 2 | [1, 2] -> [2, 1] | Add 2, rotate 1 element |
| pop | - | [1] | Pop front (2) |
| empty | - | [1] | Check if empty |
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.