Data Structures · Visualization
Stack/Queue Duals: Introduction
Stack/Queue Duals
Stacks (LIFO) and queues (FIFO) can impersonate each other using two of the other kind. Time: O(1) amortised per operation. Space: O(n).
Big-O: O(1) amortised via lazy transfers.
Stack/Queue Duals: Introduction
Stack/Queue DualsStacks (LIFO) and queues (FIFO) can impersonate each other using two of the other kind. The trick is always the same: park items in one container, and only shuffle them into the second when you must serve — the shuffle reverses the order, converting LIFO to FIFO or back. Each item moves at most twice, so the cost stays constant on average.
How Stack/Queue Duals: Introduction Works
- Keep two containers: an 'inbox' for arrivals and an 'outbox' for serving.
- New items always land in the inbox.
- Serve from the outbox; if it is empty, pour the whole inbox over first.
- The pour reverses order once — exactly the LIFO↔FIFO conversion needed.
Stack/Queue Duals: Introduction Worked Example
Input: Enqueue 1, 2, 3 then dequeue twice (two stacks)
- Inbox (stack): [1, 2, 3], outbox empty.
- Dequeue → outbox empty, pour: outbox becomes [3, 2, 1]-top-first.
- Pop outbox → 1, then 2. Inbox untouched.
- FIFO order preserved with plain stacks.
Output: Dequeued: 1, 2 — queue order from two LIFO stacks
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: introStack/Queue Duals: Introduction Time & Space Complexity
When to Use Stack/Queue Duals: Introduction
- Interview favourite: building queues where only stacks exist
- Undo buffers that must replay oldest-first
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.