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 Duals

Enqueue 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

  1. enqueue(x): push x onto inbox stack.
  2. dequeue(): if outbox is non-empty, pop it.
  3. If outbox is empty: pop every inbox item onto outbox (reverses order), then pop.
  4. Peek works like dequeue without removing.

Queue from Two Stacks Worked Example

Input: enqueue 10, enqueue 20, dequeue, enqueue 30, dequeue

  1. Inbox: [10, 20], outbox: [].
  2. Dequeue β†’ pour β†’ outbox [20, 10]-top-first β†’ serve 10.
  3. Enqueue 30 β†’ inbox [30].
  4. Dequeue β†’ outbox still has 20 β†’ serve 20.

Output: Served in order: 10, 20 β€” inbox holds [30]

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: queue
Input: enqueue 10, enqueue 20, dequeue, enqueue 30, dequeue

Behind 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

TimeO(1) amortised; O(n) worst single dequeue (the pour)
SpaceO(n)

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

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.