4. Queues (Two-Stack Queue)
First in, first out. Enqueue at the back, dequeue at the front. In Python use collections.deque; the classic interview twist builds a queue from two stacks.
How it works
A queue serves items in arrival order, which is exactly what breadth-first search, task schedulers and buffers need.
Queue from two stacks: push new items onto inbox. To dequeue, pop from outbox; if outbox is empty, first pour every item from inbox into outbox, which reverses their order so the oldest item ends up on top. Each item is moved at most once, so every operation is amortized O(1).
Diagram
flowchart LR
E["enqueue x"] --> I["inbox stack"]
I -->|"only when outbox is empty: pop all and push"| O["outbox stack"]
O --> D["dequeue returns the top of outbox"]
Step-by-step trace
Input: Run enqueue 1, 2, 3, dequeue, enqueue 4, then three dequeues.
| Operation | Returns | Moved inbox -> outbox? | inbox (top at right) | outbox (top at right) |
|---|---|---|---|---|
| enqueue(1) | - | no | [1] | [] |
| enqueue(2) | - | no | [1, 2] | [] |
| enqueue(3) | - | no | [1, 2, 3] | [] |
| dequeue() | 1 | yes | [] | [3, 2] |
| enqueue(4) | - | no | [4] | [3, 2] |
| dequeue() | 2 | no | [4] | [3] |
| dequeue() | 3 | no | [4] | [] |
| dequeue() | 4 | yes | [] | [] |
Result: Values come out as [1, 2, 3, 4], the same order they went in.
Complexity
| Operation | Time | Space |
|---|---|---|
| Enqueue | O(1) | O(1) |
| Dequeue (amortized) | O(1) | O(1) |
| Dequeue (worst single call) | O(n) | O(1) |
| deque append / popleft | O(1) | O(1) |
Python reference implementation
class TwoStackQueue:
"""FIFO queue built from two LIFO stacks; amortized O(1) per operation."""
def __init__(self):
self.inbox = []
self.outbox = []
def enqueue(self, value):
self.inbox.append(value)
def dequeue(self):
if not self.outbox:
while self.inbox:
self.outbox.append(self.inbox.pop())
if not self.outbox:
raise IndexError("dequeue from empty queue")
return self.outbox.pop()
Common mistakes and tips
list.pop(0)is O(n); a real queue in Python iscollections.deque.- Only pour inbox into outbox when outbox is empty, or the order breaks.
- A circular buffer gives a fixed-capacity queue with O(1) operations and no allocation.
The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.
| Previous: Stacks (Balanced Brackets) | Next: Hash Tables (Separate Chaining) |