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 Duals

Stacks (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

  1. Keep two containers: an 'inbox' for arrivals and an 'outbox' for serving.
  2. New items always land in the inbox.
  3. Serve from the outbox; if it is empty, pour the whole inbox over first.
  4. 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)

  1. Inbox (stack): [1, 2, 3], outbox empty.
  2. Dequeue → outbox empty, pour: outbox becomes [3, 2, 1]-top-first.
  3. Pop outbox → 1, then 2. Inbox untouched.
  4. FIFO order preserved with plain stacks.

Output: Dequeued: 1, 2 — queue order from two LIFO stacks

📖 Introduction: this is an overview of the topic, so there's nothing to run here. Pick an operation from the side menu to see a live, step-by-step animation.
Duals: Introduction
Two containers impersonating the third: pour to serve, reversing order once.
Inbox stack
empty
push end
Outbox stack
empty
pop end
Next to serve
Duals: Introduction
Write a script (or use +/−) then press ▶ Run.
Python · Stack/Queue Duals in Code
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: intro

Stack/Queue Duals: Introduction Time & Space Complexity

TimeO(1) amortised per operation
SpaceO(n)

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.