Stacks and queues · Exercise 66 of 100

Queue using two stacks

Push new arrivals onto an input stack and remove items from an output stack. When a removal is requested and the output stack is empty, move every input item onto it one at a time, reversing their order so the oldest ends up on top. If both stacks are empty, there is nothing to remove.

Try it yourself

Both stacks start empty. Enqueue 5 and 8, dequeue once, then enqueue 11 and 14. Using the transfer rule above, how many items move from input to output during the next two dequeues combined?

One-step hint

Draw both stacks just after the first dequeue. Across the next two dequeues, count an item only when an empty output stack forces it to cross over.

Worked solution
  1. The initial dequeue transfers 8 and 5, then removes 5. With 8 still on the output stack, the first of the next two dequeues removes 8 without moving any items between stacks.
  2. The last dequeue finds the output stack empty, so it transfers 14 and then 11 before removing 11. Those two dequeues transfer 2 items in total.
DSA compiler