Queue Using Stacks | Data Structures Interview | Skill-Lync Resources
Medium Data Structures Stacks & Queues

How do you implement a queue using two stacks?

Answer

Use two stacks: inbox for enqueue, outbox for dequeue. Enqueue pushes to inbox (O(1)). Dequeue pops from outbox; if outbox is empty, transfer all elements from inbox (reversing order) then pop. Each element is moved at most twice, giving amortized O(1) per operation. This approach is useful when stack operations are the only primitives available or for certain distributed scenarios.

Master These Concepts with IIT Certification
IIT Certified

Master These Concepts with IIT Certification

175+ hours of industry projects. Get placed at Bosch, Tata Motors, L&T and 500+ companies.

Relevant for Roles

Software Engineer Backend Developer Application Developer