Learn / Stacks and queues

Queue using stacks

A queue from two stacks: push onto an input stack; when the output stack is empty, pour the input into it, which reverses the order so the oldest item is on top. Each item moves at most twice, so operations are O(1) amortised. A stack from one queue: after adding x, rotate the older items behind it.

How to recognise it

  • The problem only lets you use one of the two structures.
  • You must turn LIFO into FIFO, or the other way round.
  • Amortised O(1) is allowed.

Queue from two stacks

push(x): in.push(x)
peek():  if out is empty: move everything from in to out
         return out.top
pop():   peek(); return out.pop

The input stack has the newest on top. Moving it into the output stack flips it, so the oldest is on top there. Items already in the output are older than anything in the input, so the output must be used up before pouring again.

Each item is pushed and popped at most twice in total, so n operations cost O(n): O(1) each on average.

Stack from one queue

push(x): add x; then repeat size - 1 times: add(remove())

Every push rotates the older items behind the new one, so the front of the queue is always the most recent item. Push is O(n) and pop is O(1). Using two queues gives the same costs with more code.

Common mistakes

  • Pouring on every operation, which breaks the order.
  • Checking only the input stack in empty().

Problems

0 of 2 solved

Check yourself

Push 1, 2, 3 onto the input stack, then pour into the output stack. What is on top of the output?

When should you pour the input stack into the output stack?

For a stack built from one queue, how many rotations follow pushing x onto a queue of size s after adding it?