Implement Queue using Stacks
Implement a FIFO queue using two LIFO stacks with amortized O(1) push, pop, and peek operations via lazy pouring.
01The problem
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).
Implement the MyQueue class:
void push(int x)Pushes element x to the back of the queue.int pop()Removes the element from the front of the queue and returns it.int peek()Returns the element at the front of the queue.boolean empty()Returnstrueif the queue is empty,falseotherwise.
You must use only standard stack operations: push to top, peek/pop from top, size, and is empty.
| Input Operations | Output | Why |
|---|---|---|
push(1), push(2), peek() | 1 | 1 was pushed first, so it is at the front |
pop() | 1 | Removes and returns front element 1 |
empty() | false | 2 remains inside the queue |
Constraints: 1 <= x <= 9, at most 100 calls. All calls to pop and peek are valid.
02How to spot it
- A queue requires FIFO order (first in, first out).
- A stack provides LIFO order (last in, first out).
- Pouring elements from one stack to another reverses their order: LIFO reversed becomes FIFO!
- Pouring on every push or pop is expensive (
O(n)per operation). - Solution: Maintain two stacks: an inbox and an outbox. Pour lazily only when outbox runs dry.
So: two stacks with lazy transfer.
03Pseudocode
push(x): in.push(x)
peek():
if out empty:
move everything from in to out
return out.top
pop(): peek(); return out.pop()
empty(): both stacks empty- New items always go into the
instack (inbox). - Need the front item? Look in the
outstack (outbox). - If
outis empty, pour all elements fromintoout(reversing their order). - Both stacks must be empty for the queue to be empty.
04Watch it work
inbox stack (pushes)
outbox stack (pops/peeks)
operation
init
Queue using two stacks: `in` stack receives pushes, `out` stack serves pops and peeks in FIFO order.
Pseudocode
- push(x): in.push(x)
- peek():
- if out empty:
- move everything from in to out
- return out.top
- pop(): peek(); return out.pop()
- empty(): both stacks empty
Variables
- in
- out
05Step-by-step dry run
- 1
inbox stack (pushes)
outbox stack (pops/peeks)
operation
init
Queue using two stacks: `in` stack receives pushes, `out` stack serves pops and peeks in FIFO order.
in = out =
- 2
inbox stack (pushes)
10topoutbox stack (pops/peeks)
operation
push(1)
Push 1 onto inbox stack.
op = pushval = 1
- 3
inbox stack (pushes)
1021topoutbox stack (pops/peeks)
operation
push(2)
Push 2 onto inbox stack.
op = pushval = 2
- 4
inbox stack (pushes)
outbox stack (pops/peeks)
2011topoperation
peek: pour in -> out
Outbox is empty: poured all elements from inbox to outbox, reversing their order to FIFO.
inCount = 0outCount = 2
- 5
inbox stack (pushes)
outbox stack (pops/peeks)
2011topoperation
peek -> 1
Peek front element: 1.
front = 1
- 6
inbox stack (pushes)
outbox stack (pops/peeks)
20topoperation
pop -> 1
Popped front element 1 from outbox.
popped = 1
- 7
inbox stack (pushes)
outbox stack (pops/peeks)
20topoperation
empty -> false
Check empty: false. Both stacks have elements.
isEmpty = false
06Java solution
import java.util.ArrayDeque;
import java.util.Deque;
public class MyQueue {
private final Deque<Integer> in = new ArrayDeque<>();
private final Deque<Integer> out = new ArrayDeque<>();
public void push(int x) {
in.push(x);
}
public int pop() {
peek();
return out.pop();
}
public int peek() {
if (out.isEmpty()) {
while (!in.isEmpty()) {
out.push(in.pop());
}
}
return out.peek();
}
public boolean empty() {
return in.isEmpty() && out.isEmpty();
}
public static void main(String[] args) {
MyQueue q = new MyQueue();
q.push(1);
q.push(2);
System.out.println(q.peek());
System.out.println(q.pop());
System.out.println(q.empty());
}
}1 1 false
07Why it works
Pouring from in to out flips the order of elements: the oldest element in in (at the bottom) becomes the newest element in out (at the top).
Crucially, we only pour when out is completely empty. If out already has elements, pouring new ones onto it would place newer elements above older elements, breaking FIFO order. By waiting until out empties, every element is transferred across the two stacks exactly once in its lifetime.
08Time and space
- Time complexity:
push:O(1).popandpeek: AmortizedO(1), worst-caseO(n). Each element is pushed ontoinonce, popped frominonce, pushed ontooutonce, and popped fromoutonce. Total work fornoperations is4n = O(n), averagingO(1)per call.empty:O(1).
- Space complexity:
O(n)to storenelements distributed between the two stacks.
09Edge cases
- Alternating pushes and pops: Correctly handled because
pushnever touchesout, andpoponly drainsinwhenoutis empty. - Multiple
peekcalls in a row: The firstpeekpours elements; subsequent calls immediately returnout.peek()inO(1). - Empty queue check: Must verify both stacks (
in.isEmpty() && out.isEmpty()).
10Common mistakes
- Refilling
outwhen it is not empty. Ifouthas elements and you pourininto it, the newer elements frominsit above older elements inout, corrupting FIFO order. - Transferring back from
outtoinon push. Some naive designs pour back and forth on every operation. That turns every push and pop into an expensiveO(n)operation.
11Other approaches
| Approach | Push time | Pop time | Space | Note |
|---|---|---|---|---|
| Pour on push | O(n) | O(1) | O(n) | Heavy push, always keeps elements in pop order |
| Lazy pour on pop/peek | O(1) | O(1) amortized | O(n) | Optimal standard design |
12In the interview
13Check your understanding
Quiz · 2 questions
0 of 2 answered
1. Why must we only pour elements from in to out when out is completely empty?
2. What is the amortized time complexity of pop() in this two-stack queue?
14Solve it yourself
Try implementing a stack using two FIFO queues (MyStack):
- How does the order reversal change when queues are the primitive?
- Can
pushorpopbeO(1)amortized?