Data Structures Β· Visualization
Stack/Queue Duals: Queue from Two Stacks
Stack/Queue Duals
Enqueue pushes onto stack A. Time: O(1) amortised; O(n) worst single dequeue (the pour). Space: O(n).
Big-O: O(1) amortised via lazy transfers.
Stack/Queue Duals: Queue from Two Stacks
Stack/Queue DualsEnqueue pushes onto stack A. Dequeue pops stack B β and only when B is empty do we pop all of A into B. That single lazy transfer is the whole insight: every element is pushed twice and popped twice across its lifetime, so each operation costs O(1) on average no matter how long the queue grows.
How Queue from Two Stacks Works
- enqueue(x): push x onto inbox stack.
- dequeue(): if outbox is non-empty, pop it.
- If outbox is empty: pop every inbox item onto outbox (reverses order), then pop.
- Peek works like dequeue without removing.
Queue from Two Stacks Worked Example
Input: enqueue 10, enqueue 20, dequeue, enqueue 30, dequeue
- Inbox: [10, 20], outbox: [].
- Dequeue β pour β outbox [20, 10]-top-first β serve 10.
- Enqueue 30 β inbox [30].
- Dequeue β outbox still has 20 β serve 20.
Output: Served in order: 10, 20 β inbox holds [30]
Write a script (or use +/β) then press βΆ Run.
inbox, outbox = [], [] # two stacks
def enqueue(x): inbox.append(x)
def dequeue():
if not outbox: # pour only when empty
while inbox: outbox.append(inbox.pop())
return outbox.pop() # O(1) amortised
# example: queueBehind 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.
Queue from Two Stacks Time & Space Complexity
When to Use Queue from Two Stacks
- Message queues on platforms exposing only stack primitives
- Breadth-first search frontiers built over call-stack-like storage
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.