Two Stacks Build An Amortized Queue

Build a FIFO queue from two stacks: pour the inbox once when the outbox empties, so every element moves at most twice and operations stay amortized O(1).

PythonData Integrity

Code

pythonsnippet
30 lines
# Queue from two stacks: push onto the inbox; when the outbox is
# empty, pour the whole inbox over once, then pop from the outbox.
# Each element moves at most twice, so n operations cost O(n) total —
# amortized O(1) per operation — and FIFO order is preserved.
class TwoStackQueue:
    def __init__(self):
        self.inbox = []
        self.outbox = []

    def push(self, value):
        self.inbox.append(value)

    def pop(self):
        if not self.outbox:
            while self.inbox:
                self.outbox.append(self.inbox.pop())
        return self.outbox.pop()

    def __len__(self):
        return len(self.inbox) + len(self.outbox)


queue = TwoStackQueue()
for item in ('a', 'b', 'c'):
    queue.push(item)

print('pop order:', queue.pop(), queue.pop())
queue.push('d')
print('pop order:', queue.pop(), queue.pop())
print('remaining:', len(queue))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

pop order: a b
pop order: c d
remaining: 0

How it works

Structurally, expect the class TwoStackQueue and the functions __init__, push, pop and __len__ and nothing else.

The cycling part of this snippet is while self.inbox.

Points of care

  • Standard-library end to end — copy it in and it runs.

Using it

The primary signature, spelled out, is def push(self, value)

The demo output is labeled (pop order:, remaining:), so every line of output can be traced to the operation that made it.

Treat push as the API: import it, and ignore the supporting code.

The key statements that remain

def push(self, value):
    self.inbox.append(value)
def __init__(self):
    self.inbox = []
    self.outbox = []
def __len__(self):
    return len(self.inbox) + len(self.outbox)

Interactive Tools for This Topic

FAQ

Can I paste this into a project as-is?
Yes. Paste it in and run; no package manager step is needed. The file defines `__init__`, `push`, `pop` at load time.