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 Duals

Push 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

  1. push(x): enqueue x onto the main queue.
  2. Then move each older item to the back, one by one.
  3. Now x sits at the front β€” pop is just dequeue.
  4. 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

  1. Push 5 β†’ main [5]. Push 7 β†’ enqueue β†’ [5, 7] β†’ rotate 5 back β†’ [7, 5].
  2. Pop β†’ dequeue 7.
  3. Push 9 β†’ [5, 9] β†’ rotate β†’ [9, 5].
  4. LIFO order: 7 served before 5, 9 on top.

Output: Popped: 7 β€” stack order from FIFO queues

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
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: stack
Input: push 5, push 7, pop, push 9

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.

Stack from Two Queues Time & Space Complexity

TimeO(n) push, O(1) pop (or O(1)/O(n) swapped with the lazy variant)
SpaceO(n)

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

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.