Build a queue from two stacks. Why is it O(1) amortized?
Question
A delivery app needs a first-in, first-out queue of orders, but you may only use stacks. A Python list counts as a stack if you use only append and pop().
Write a class TwoStackQueue with push(item) and pop(), using two lists. pop() on an empty queue raises IndexError. Then explain why each operation is O(1) amortized, even though one pop() can be slow.
q = TwoStackQueue() for order in (101, 102, 103): q.push(order) q.pop() # 101 q.push(104) q.pop() # 102 q.pop() # 103 q.pop() # 104
class TwoStackQueue: def __init__(self): self.inbox, self.outbox = [], [] def push(self, item): ... def pop(self): ...
Show hints (3)
- "FLIP THE ORDER"
Pop plates one by one from a stack and put them on a second stack. The order flips, and the plate that went in first is now on top.
- "TWO ROLES"
Use
inboxfor new orders andoutboxfor orders that are ready to leave.pushalways goes toinbox.popalways takes fromoutbox. - "WHEN TO MOVE"
Move items only when
outboxis empty, and then move all of them. Ifoutboxstill holds orders, they are older than anything ininbox.
Show checked explanation
Push onto inbox. Pop from outbox. When outbox is empty, move every item from inbox to outbox, which reverses them, so the oldest is on top. Each item moves at most once, so n pushes and pops cost O(n) in total: O(1) amortized. A single pop() can still cost O(n).
class TwoStackQueue: def __init__(self): self.inbox, self.outbox = [], [] def push(self, item): self.inbox.append(item) def pop(self): if not self.outbox: # refill only when empty, and move everything while self.inbox: self.outbox.append(self.inbox.pop()) return self.outbox.pop() # IndexError when the queue is empty q = TwoStackQueue() for order in (101, 102, 103): q.push(order) print(q.pop(), q.inbox, q.outbox) q.push(104) # waits in inbox: 102 and 103 are older print(q.pop(), q.pop(), q.pop())
101 [] [103, 102] 102 103 104
Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.
Walkthrough
Here is the example, step by step. The top of each stack is on the right.
| step | inbox | outbox | returns |
|---|---|---|---|
| push 101, 102, 103 | [101, 102, 103] | [] | |
| pop: refill, moves 3 | [] | [103, 102] | 101 |
| push 104 | [104] | [103, 102] | |
| pop | [104] | [103] | 102 |
| pop | [104] | [] | 103 |
| pop: refill, moves 1 | [] | [] | 104 |
Moving items from one stack to the other reverses their order. So after the first refill, the oldest order, 101, is on top of outbox.
Look at the push of 104. It goes into inbox and waits there. 102 and 103 are older, so they must leave first. That is why you refill only when outbox is empty. And when you refill, you move everything, because the oldest item sits at the bottom of inbox.
Why O(1) amortized? Follow one order through its life. It is appended to inbox once, popped from inbox at most once, appended to outbox at most once and popped from outbox once. That is at most 4 stack operations per order. In the example, 4 orders cost 16 stack operations over 8 queue calls. In general, any sequence of calls that starts with an empty queue and pushes n items costs at most 4n stack operations.
The first pop() above was the expensive one: 3 moves plus the pop itself. With k items in inbox and an empty outbox, one pop() costs 2k + 1 stack operations: O(k). Amortized O(1) promises a small total, not a small cost for every single call. It holds for every sequence of calls, with no luck or random input involved.
Common mistakes
- Moving items while
outboxis not empty. After the push of 104, moving it onto[103, 102]gives[103, 102, 104], and the nextpop()returns 104 before 102. - Moving only one item. With
inbox = [101, 102, 103], moving one puts 103 onoutbox, sopop()returns the newest order instead of the oldest. - Moving everything back to
inboxafter eachpop(). The order stays right, but every pop moves the whole queue twice: O(n) per call. - Returning
Nonefrom an empty queue. Then a storedNonelooks the same as "empty". RaiseIndexError, aslist.pop()does.
Follow-up questions
- "How do you add
peek()?" Do the same refill, then returnself.outbox[-1]without popping it. A peek may move items too, but each item still moves only once, so the 4n bound still holds. - "Each request must be fast, not just fast on average. Is this queue good enough?" Not always. The pop that refills moves every waiting item. After 1,000,000 pushes, one pop moves 1,000,000 items. If every call needs a small time limit, use
collections.deque: itsappendandpopleftare O(1) on every call. - "Why learn this if Python has
deque?" In Python code, usedeque. The idea still matters when each stack carries extra data. Build this queue from two min stacks. Its minimum is the smaller of the two stack minimums, so you read it in O(1).
What a strong answer covers
States the rule before coding: refill only when outbox is empty, and move everything. Proves O(1) amortized by counting at most 4 stack operations per item. Says one pop can still be O(n), and uses deque in real code.
Open in interactive practice deck →