Medium Data Structures Stacks & Queues
How would you implement a stack using two queues?
Answer
Use two queues q1 and q2. For push: add element to q2, then move all elements from q1 to q2, then swap q1 and q2. For pop: simply dequeue from q1. This makes push O(n) and pop O(1). Alternative approach: make push O(1) and pop O(n) by adding to q1 directly, and for pop, move all except last element to q2, dequeue last, then swap.
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