AlgoScope

Queue Using Two Stacks

AlgorithmintermediateQueue Patterns

Enqueue onto an in stack; when the out stack is empty, pour everything across to reverse the order.

Decision · step 5 of 16Queue: Queue from two stacks
bottomtopinout5!3!9!

dequeue: the out stack is empty, so the front of the queue is buried at the bottom of in. Pour: pop every item off in and push it onto out, 5, 3, 9 in that order, which puts 5, the oldest, on top of out.

Open in the player →or start at step 5

What you will see

Items pour from one stack to the other, reversing; the pour is amortized O(1).

How queue works →

Cost

BestO(1)
AverageO(1) amortized
WorstO(n)
SpaceO(n)

How you work with it here

play it through, step one change at a time, scrub to any step, run it on your own input, predict what happens next, try operations in any order.

Screen readers: Items announce position from the top or front and value; each step announces the operation and the new top or front.

Reduced motion: Items appear or disappear in place with a crossfade instead of sliding in or out.

Taught by the same lesson

Queue covers these too, in the same run.