Data Structures Β· Visualization
Stack/Queue Duals: Stack from Two Queues
Stack/Queue Duals
Push rotates the newcomer to the front: enqueue it, then dequeue-and-enqueue every older item behind it. Time: O(n) push, O(1) pop (or O(1)/O(n) swapped with the lazy variant). Space: O(n).
Big-O: O(1) amortised via lazy transfers.
Stack/Queue Duals: Stack from Two Queues
Stack/Queue DualsPush rotates the newcomer to the front: enqueue it, then dequeue-and-enqueue every older item behind it. The main queue always keeps newest-first order, so pop is a plain dequeue. Push costs O(n) per item here β the mirror image of the queue-from-stacks trade-off.
How Stack from Two Queues Works
- push(x): enqueue x onto the main queue.
- Then move each older item to the back, one by one.
- Now x sits at the front β pop is just dequeue.
- The helper queue (or a size counter) makes the rotation exact.
Stack from Two Queues Worked Example
Input: push 5, push 7, pop, push 9
- Push 5 β main [5]. Push 7 β enqueue β [5, 7] β rotate 5 back β [7, 5].
- Pop β dequeue 7.
- Push 9 β [5, 9] β rotate β [9, 5].
- LIFO order: 7 served before 5, 9 on top.
Output: Popped: 7 β stack order from FIFO queues
Write a script (or use +/β) then press βΆ Run.
from collections import deque
q = deque()
def push(x):
q.append(x)
for _ in range(len(q) - 1):
q.append(q.popleft()) # rotate newcomer front
def pop(): return q.popleft() # O(1)
# example: stackBehind the Scenes Execution
Press βΆ Run in the visualizer β the call stack, registers and memory will replay here in sync with the code, line by line.
Stack from Two Queues Time & Space Complexity
When to Use Stack from Two Queues
- Depth-first search where only queue hardware exists
- Browser-history back-stacks over message-passing channels
Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action β visualize the algorithms that operate on these structures, or take a guided course.