Skip to content
Preptima
mediumCodingConceptEntryMidSenior

Implement a FIFO queue using only two stacks, then tell me what a dequeue costs.

4 min readUpdated 2026-08-15Target archetype: Big Tech, Enterprise Captive, Product Startup

Answer

Short answer

Push arrivals onto an inbound stack and serve departures from an outbound one, transferring everything across only when the outbound stack is empty. Transferring on every dequeue instead reverses the order and breaks FIFO, and the empty-only rule is also what makes the amortised cost constant.

Was this answer helpful?

Likely follow-ups

  • Give me a worst-case constant-time dequeue instead of an amortised one. What do you have to give up?
  • Implement a stack from two queues. Which operation gets expensive, and why is it not symmetric?
  • Two threads share this queue. Where exactly does it break?
  • Add a constant-time minimum query to the queue. What extra state do you keep?

Related questions