Queues from Stacks: Amortized & Real-Time
Two-stack queues, their amortized cost, and worst-case O(1) functional queues.
Two stacks make a queue: push onto one, pop from the other, and pour the first into the second when the second runs dry. Every operation costs on average, yet a single dequeue can cost a million steps, and if old versions of the queue are kept and reused, even the average guarantee collapses. Repairing both took a surprising tool: lazy evaluation.
What you’ll learn
- Prove the two-stack queue's amortized bound with a potential function, and exhibit the operation that costs .
- Explain why persistence breaks amortized analysis, and how memoized lazy evaluation repairs it.
- Implement Okasaki's real-time queue and prove that every operation takes worst-case time, even when old versions are reused.
- Place Hood–Melville queues, global rebuilding, real-time deques and Kaplan–Tarjan catenable deques in context, together with what is known about pure versus impure efficiency.
The two-stack queue and its potential
Count the cost of an operation as the number of stack pushes and pops it performs. A queue built from an inbox stack and an outbox stack works like this:
class TwoStackQueue:
def __init__(self):
self.inbox, self.outbox = [], []
def enqueue(self, x): # 1 push
self.inbox.append(x)
def dequeue(self):
if not self.outbox: # refill: k pops and k pushes
while self.inbox:
self.outbox.append(self.inbox.pop())
return self.outbox.pop() # 1 pop; IndexError if the queue is emptyMoving the inbox over reverses it, so the oldest item ends up on top of the outbox. A refill happens only when the outbox is empty, which is what keeps the order first in, first out.
Enqueue into an empty two-stack queue, then dequeue once. How many stack pushes and pops does that single dequeue perform?
Show the answer
2001 steps
The outbox is empty, so all 1000 items move: 1000 pops and 1000 pushes, then one more pop returns item 1. That is steps, for one operation. The next 999 dequeues cost one step each.
Amortized cost is the actual cost plus the change in the potential, . Summed over a sequence, the potential telescopes:
Enqueue does one push and grows the inbox by one:
Dequeue without a refill does one pop and leaves the inbox alone:
Dequeue with a refill of items does steps and empties the inbox, so the stored potential pays for the move. Every amortized cost is exactly 3 or 1, which gives the exact total :
Think first Why and not ?
With , a refill of items would cost amortized: not a constant. Each item must prepay both steps of its future move, the pop from the inbox and the push onto the outbox. The potential is a prepayment: each enqueue pays 3, one step for its own push and two saved for the move.
Persistence breaks amortization
In a functional language, values are immutable: an operation returns a new queue and the old one stays valid. A persistent queue lets you keep both, and that breaks the argument above. Here is the same idea as the two-stack queue, the batched queue, built from immutable lists (Gries, 1981; Hood & Melville, 1981; Burton, 1982): a front list , and a rear list stored in reverse, with the rule that is empty only if the whole queue is.
def rev(lst): # reverse a linked list of pairs: linear time
out = None
while lst is not None:
out, lst = (lst[0], out), lst[1]
return out
def check(f, r): # invariant: f is empty only if the queue is
return (rev(r), None) if f is None else (f, r)
def snoc(q, x): return check(q[0], (x, q[1])) # add at the back
def head(q): return q[0][0]
def tail(q): return check(q[0][1], q[1]) # remove the frontLists are nested pairs (head, rest), so versions share structure and nothing is ever modified. Used ephemerally, snoc and tail are amortized by the same potential argument.
Okasaki's insight (1995–1998) was to replace savings by debt. Make the reversal a memoized suspension: a computation that is not performed until its result is demanded, and whose result is cached once computed. Every future that shares the suspension shares its result, so the expensive reversal runs at most once, however many versions demand it. In his banker's method, each suspension carries a debt equal to its cost, and an operation may force a suspension only after enough cheap operations, along every path of operations leading to it, have paid that debt off.
His banker's queue keeps , and when the rear becomes one longer than the front it replaces by the suspension . The reversal is forced only after more tails have walked through the old front, and those tails pay for it, so every operation is amortized even under persistence. One operation can still be expensive: the one that finally forces the reversal.
Real-time queues: schedule the work
An operation that forces a whole reversal still takes . A queue is a real-time queue if every operation takes in the worst case. Okasaki (1995) got there in two moves.
First, make the rotation incremental: rotate(f, r, a) computes one list cell at a time, each cell a suspension that does work and moves one item of onto the accumulator . Second, keep a schedule , a pointer into marking its first cell not yet forced, and force one more cell on every operation. The invariant makes the schedule run out exactly when , which is when the next rotation must begin.
class Lazy: # a memoized suspension
def __init__(self, thunk): self.thunk, self.value = thunk, None
def force(self):
if self.thunk is not None:
self.value, self.thunk = self.thunk(), None
return self.value # None = empty stream, else (head, stream)
NIL = Lazy(lambda: None)
def rotate(f, r, a): # f ++ reverse(r) ++ a, when |r| = |f| + 1
def step():
cell = f.force()
if cell is None:
return (r[0], a) # r holds exactly one item here
return (cell[0], rotate(cell[1], r[1], Lazy(lambda: (r[0], a))))
return Lazy(step)
def make(f, r, s): # keep |s| = |f| - |r|: force one cell of s
cell = s.force()
if cell is not None:
return (f, r, cell[1])
f2 = rotate(f, r, NIL) # schedule exhausted: start a rotation
return (f2, None, f2)
EMPTY = (NIL, None, NIL)
def snoc(q, x): return make(q[0], (x, q[1]), q[2])
def head(q): return q[0].force()[0]
def tail(q): return make(q[0].force()[1], q[1], q[2])A transcription of Okasaki's Standard ML code: the front is a lazy stream, the rear an ordinary list of pairs, and the schedule a suffix of . Each operation runs at most one suspension body, the first unforced cell of the schedule, and that body does work; instrumenting the code confirms it, both in ephemeral use and when old versions are operated on over and over.
Invariant. , and every cell of before has been forced.
snoclengthens andtailshortens , so whenmakeruns, . Dropping one cell of restores the invariant; if is already empty, then , exactly the precondition ofrotate.Each suspension is cheap. A rotation cell does work of its own plus forcing the first cell of the old front. That old front is a suffix of the front built by the previous rotation, all of whose cells the schedule forced before ran out, so forcing it is a memo lookup.
Each operation forces at most one new suspension: the first cell of , because every earlier cell of is already forced. Forced cells stay forced for every version that shares them, so the bound holds for every version, however versions are reused.
What does the schedule guarantee in Okasaki's real-time queue?
- That the whole front list is always fully evaluated
- That every cell of the front is forced before the next rotation needs it, so each rotation step is a memo lookup plus work
- That the queue never has to be rotated
- That each version of the queue is used at most once
Show the answer
B. That every cell of the front is forced before the next rotation needs it, so each rotation step is a memo lookup plus work
One cell of is forced per operation, and operations remain before the next rotation must start: enough to force every cell of . When the rotation later walks that front, each step finds its cell memoized, so no operation triggers a chain of evaluations.
Okasaki was not the first to reach worst-case time. Hood and Melville (1981) built real-time queues in pure Lisp with no laziness at all, using what Overmars (1983) named global rebuilding: start building the reversed rear well before the front runs out, advance the copy by a constant number of steps on every operation, and keep enough bookkeeping to discard copies of items that are dequeued meanwhile. It works and it is persistent, but it is considerably more intricate; laziness plus a schedule packs the same idea into a few lines. The Foundations lesson Deamortization & Global Rebuilding develops the general technique.
Deques, catenation, and the price of purity
| Queue | Worst case per operation | Amortized | When old versions are reused |
|---|---|---|---|
| Circular buffer (imperative) | ; for a resize if it grows | not possible: it is updated in place | |
| Two stacks, or the batched queue | breaks: per operation | ||
| Banker's queue (lazy) | amortized, by debits and memoization | ||
| Real-time queue (lazy plus a schedule) | worst case | ||
| Hood–Melville queue (global rebuilding) | worst case, with no laziness |
Deques. Hood (1982) extended the Hood–Melville construction to real-time deques, and Okasaki (1995) gave lazy real-time deques with the same scheduling idea, keeping the two ends balanced within a constant factor so that either end can be refilled from the other in time.
Catenation is harder: joining two deques in rules out copying either one. Kaplan and Tarjan (STOC 1995; Journal of the ACM, 1999) achieved purely functional, real-time deques with catenation, every operation in the worst case, by recursive slow-down, a technique related to redundant binary counters that avoid long chains of carries: no operation triggers a cascade of repairs.
Key takeaways
- The two-stack queue performs exactly stack operations for enqueues and dequeues, amortized, but one dequeue can cost .
- Amortization by savings assumes each version has a single future. Reusing an old version re-spends the same savings, and the batched queue degrades to per operation.
- Memoized lazy evaluation turns savings into debt that many futures may safely pay: Okasaki's banker's queue is amortized even under persistence.
- Incremental rotation plus a schedule that forces one suspension per operation gives real-time queues, in the worst case for every version; Hood and Melville reached the same bound earlier by global rebuilding.
- Kaplan and Tarjan's purely functional deques support catenation in worst-case time, and whether lazy functional programs can always match imperative ones is still open.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
With , what is the amortized cost of a dequeue that moves items from the inbox to the outbox?
Show the answer
B.
The actual cost is ( pops, pushes and the final pop) and , so . The steps of the move were prepaid by the enqueues, 2 each.
Why does the amortized bound of the batched (two-list) queue fail when old versions are reused?
- The same expensive version can be operated on again and again, but its prepaid savings can be spent only once
- Immutable lists make every operation take
- Reversing an immutable list takes time
- Persistence forces a deep copy of the queue on every operation
Show the answer
A. The same expensive version can be operated on again and again, but its prepaid savings can be spent only once
The potential argument charges each reversal to earlier cheap operations along a single history. A version with a long rear list has many possible futures, and each call of tail on it reverses the same list again and pays in full, so such calls cost .
Lazy evaluation fixes the persistent banker's queue only if suspensions are memoized. What goes wrong with plain call-by-name suspensions, which recompute their result on every demand?
- Nothing: delaying the reversal is enough
- The queue returns items in the wrong order
- Suspensions can never be forced
- Every logical future that demands the same suspension redoes the reversal, so the work is done many times over
Show the answer
D. Every logical future that demands the same suspension redoes the reversal, so the work is done many times over
The banker's argument lets many futures pay the same debt, but the actual work must happen once. Memoization caches the reversed list inside the shared suspension, so the second and later demands find it ready.
What does Okasaki's real-time queue guarantee that his banker's queue does not?
- Catenation of two queues in
- Persistence
- time for every operation in the worst case, not just amortized
- Freedom from lazy evaluation
Show the answer
C. time for every operation in the worst case, not just amortized
The banker's queue forces a whole reversal at once, for that operation, though amortized even under persistence. The real-time queue rotates incrementally and forces one cell of its schedule per operation, so no operation ever costs more than a constant.
Further reading
- R. Hood & R. Melville, "Real-time queue operations in pure LISP," Information Processing Letters 13(2) (1981), 50–54.
- C. Okasaki, "Simple and efficient purely functional queues and deques," Journal of Functional Programming 5(4) (1995), 583–592.
- C. Okasaki, Purely Functional Data Structures (Cambridge University Press, 1998).
- H. Kaplan & R. E. Tarjan, "Purely functional, real-time deques with catenation," Journal of the ACM 46(5) (1999), 577–603.
- N. Pippenger, "Pure versus impure Lisp," ACM Transactions on Programming Languages and Systems 19(2) (1997), 223–238.