download

Build a queue from two stacks. Why is it O(1) amortized?

Algorithms~15 minReviewed 1 Nov 2026Free · No sign-in

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.

"PYTHON"
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
"CODE · PYTHON"
class TwoStackQueue:
    def __init__(self):
        self.inbox, self.outbox = [], []

    def push(self, item):
        ...

    def pop(self):
        ...
Show hints (3)
  1. "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.

  2. "TWO ROLES"

    Use inbox for new orders and outbox for orders that are ready to leave. push always goes to inbox. pop always takes from outbox.

  3. "WHEN TO MOVE"

    Move items only when outbox is empty, and then move all of them. If outbox still holds orders, they are older than anything in inbox.

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).

"SOLUTION · PYTHON"
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())
"OUTPUT"
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.

stepinboxoutboxreturns
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 outbox is not empty. After the push of 104, moving it onto [103, 102] gives [103, 102, 104], and the next pop() returns 104 before 102.
  • Moving only one item. With inbox = [101, 102, 103], moving one puts 103 on outbox, so pop() returns the newest order instead of the oldest.
  • Moving everything back to inbox after each pop(). The order stays right, but every pop moves the whole queue twice: O(n) per call.
  • Returning None from an empty queue. Then a stored None looks the same as "empty". Raise IndexError, as list.pop() does.

Follow-up questions

  • "How do you add peek()?" Do the same refill, then return self.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: its append and popleft are O(1) on every call.
  • "Why learn this if Python has deque?" In Python code, use deque. 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 →

Original OfferVibe question. Topic idea from Crushing the Technical Interview (Keith Henning, 2025); text, examples and code are our own.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.