The Implement Queue using Stacks interview question is a classic data structure adaptation task. You need to implement a First-In-First-Out (FIFO) queue using only two standard Last-In-First-Out (LIFO) stacks. You must support push, pop, peek, and empty operations using only the standard stack operations (push, pop, peek, size).
This is a fundamental problem used by Amazon, Microsoft, and Apple to test a candidate's understanding of how data structures manage elements. It evaluations whether you can think creatively about "reversing" data flow—since two stacks (two LIFO layers) effectively create a FIFO flow. It also tests your ability to analyze amortized time complexity.
The problem uses the Two Stacks (In and Out) pattern.
push(x): Always push to Stack 1. ()pop(): If Stack 2 is empty, transfer all elements from Stack 1 to Stack 2. This reverses their order, making the oldest element the top of Stack 2. Then pop from Stack 2.peek(): Same logic as pop, but return the top instead of removing it.push(1), push(2): Stack 1: [1, 2]. Stack 2: [].pop(): Stack 2 is empty. Transfer! Stack 1: []. Stack 2: [2, 1].
push(3): Stack 1: [3]. Stack 2: [2].pop(): Pop from Stack 2 returns 2.
Resulting order: 1, then 2. Correct FIFO behavior.empty().peek and pop instead of a reusable transferIfEmpty() helper.Explain Amortized Analysis. While a single pop might take if a transfer happens, most pop operations will take . Over operations, the total time is , meaning the average time per operation is . This distinction is what interviewers are looking for.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Implement Stack using Queues | Easy | Solve | |
| Min Stack | Medium | Solve | |
| Number of Recent Calls | Easy | Solve | |
| Flatten Nested List Iterator | Medium | Solve | |
| Design a Stack With Increment Operation | Medium | Solve |