Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

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 O(1)O(1) 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 O(1)O(1) amortized bound with a potential function, and exhibit the operation that costs Θ(n)\Theta(n).
  • 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 O(1)O(1) 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:

python
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 empty

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

Predict before you look

Enqueue 1,2,…,10001, 2, \dots, 1000 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 2k+1=20012k + 1 = 2001 steps, Θ(n)\Theta(n) for one operation. The next 999 dequeues cost one step each.

DerivationProof
  1. ∑tct  =  ∑tc^t  −  Φfinal+Φ0,Φ0=0≤Φfinal\sum_t c_t \;=\; \sum_t \hat c_t \;-\; \Phi_{\text{final}} + \Phi_0, \qquad \Phi_0 = 0 \le \Phi_{\text{final}}

    Amortized cost is the actual cost plus the change in the potential, c^t=ct+Φt−Φt−1\hat c_t = c_t + \Phi_t - \Phi_{t-1}. Summed over a sequence, the potential telescopes:

  2. c^=1+2=3\hat c = 1 + 2 = 3

    Enqueue does one push and grows the inbox by one:

  3. c^=1+0=1\hat c = 1 + 0 = 1

    Dequeue without a refill does one pop and leaves the inbox alone:

  4. c^=(2k+1)−2k=1\hat c = (2k + 1) - 2k = 1

    Dequeue with a refill of kk items does 2k+12k + 1 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 3e+d−Φfinal3e + d - \Phi_{\text{final}}:

Think first Why Φ=2 ∣inbox∣\Phi = 2\,|\text{inbox}| and not ∣inbox∣|\text{inbox}|?

With Φ=∣inbox∣\Phi = |\text{inbox}|, a refill of kk items would cost (2k+1)−k=k+1(2k + 1) - k = k + 1 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 ff, and a rear list rr stored in reverse, with the rule that ff is empty only if the whole queue is.

python
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 front

Lists are nested pairs (head, rest), so versions share structure and nothing is ever modified. Used ephemerally, snoc and tail are O(1)O(1) 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 ∣f∣≥∣r∣|f| \ge |r|, and when the rear becomes one longer than the front it replaces ff by the suspension f+ ⁣ ⁣+reverse⁡(r)f \mathbin{+\!\!+} \operatorname{reverse}(r). The reversal is forced only after ∣f∣|f| more tails have walked through the old front, and those tails pay for it, so every operation is O(1)O(1) 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 Θ(n)\Theta(n). A queue is a real-time queue if every operation takes O(1)O(1) in the worst case. Okasaki (1995) got there in two moves.

First, make the rotation incremental: rotate(f, r, a) computes f+ ⁣ ⁣+reverse⁡(r)+ ⁣ ⁣+af \mathbin{+\!\!+} \operatorname{reverse}(r) \mathbin{+\!\!+} a one list cell at a time, each cell a suspension that does O(1)O(1) work and moves one item of rr onto the accumulator aa. Second, keep a schedule ss, a pointer into ff marking its first cell not yet forced, and force one more cell on every operation. The invariant ∣s∣=∣f∣−∣r∣|s| = |f| - |r| makes the schedule run out exactly when ∣r∣=∣f∣+1|r| = |f| + 1, which is when the next rotation must begin.

python
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 ff is a lazy stream, the rear rr an ordinary list of pairs, and the schedule ss a suffix of ff. Each operation runs at most one suspension body, the first unforced cell of the schedule, and that body does O(1)O(1) work; instrumenting the code confirms it, both in ephemeral use and when old versions are operated on over and over.

DerivationProof sketch
  1. ∣s∣=∣f∣−∣r∣ ≥ 0|s| = |f| - |r| \ \ge\ 0

    Invariant. ∣s∣=∣f∣−∣r∣|s| = |f| - |r|, and every cell of ff before ss has been forced. snoc lengthens rr and tail shortens ff, so when make runs, ∣s∣=∣f∣−∣r∣+1|s| = |f| - |r| + 1. Dropping one cell of ss restores the invariant; if ss is already empty, then ∣r∣=∣f∣+1|r| = |f| + 1, exactly the precondition of rotate.

  2. cost of one rotation cell=O(1)\text{cost of one rotation cell} = O(1)

    Each suspension is cheap. A rotation cell does O(1)O(1) 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 ss ran out, so forcing it is a memo lookup.

  3. worst-case cost of each operation=O(1)\text{worst-case cost of each operation} = O(1)

    Each operation forces at most one new suspension: the first cell of ss, because every earlier cell of ff is already forced. Forced cells stay forced for every version that shares them, so the bound holds for every version, however versions are reused.

Check your understanding

What does the schedule ss guarantee in Okasaki's real-time queue?

  1. That the whole front list is always fully evaluated
  2. That every cell of the front is forced before the next rotation needs it, so each rotation step is a memo lookup plus O(1)O(1) work
  3. That the queue never has to be rotated
  4. 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 O(1)O(1) work

One cell of ss is forced per operation, and ∣s∣=∣f∣−∣r∣|s| = |f| - |r| operations remain before the next rotation must start: enough to force every cell of ff. 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 O(1)O(1) 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

QueueWorst case per operationAmortizedWhen old versions are reused
Circular buffer (imperative)O(1)O(1); Θ(n)\Theta(n) for a resize if it growsO(1)O(1)not possible: it is updated in place
Two stacks, or the batched queueΘ(n)\Theta(n)O(1)O(1)breaks: Θ(n)\Theta(n) per operation
Banker's queue (lazy)Θ(n)\Theta(n)O(1)O(1)O(1)O(1) amortized, by debits and memoization
Real-time queue (lazy plus a schedule)O(1)O(1)O(1)O(1)O(1)O(1) worst case
Hood–Melville queue (global rebuilding)O(1)O(1)O(1)O(1)O(1)O(1) 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 O(1)O(1) 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 O(1)O(1) 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 3e+d−2 ∣inbox∣3e + d - 2\,|\text{inbox}| stack operations for ee enqueues and dd dequeues, O(1)O(1) amortized, but one dequeue can cost Θ(n)\Theta(n).
  • 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 Θ(n)\Theta(n) per operation.
  • Memoized lazy evaluation turns savings into debt that many futures may safely pay: Okasaki's banker's queue is O(1)O(1) amortized even under persistence.
  • Incremental rotation plus a schedule that forces one suspension per operation gives real-time queues, O(1)O(1) 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 O(1)O(1) 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.

Question 1

With Φ=2 ∣inbox∣\Phi = 2\,|\text{inbox}|, what is the amortized cost of a dequeue that moves kk items from the inbox to the outbox?

  1. 2k+12k + 1
  2. 11
  3. k+1k + 1
  4. 33
Show the answer

B. 11

The actual cost is 2k+12k + 1 (kk pops, kk pushes and the final pop) and ΔΦ=−2k\Delta\Phi = -2k, so c^=1\hat c = 1. The 2k2k steps of the move were prepaid by the kk enqueues, 2 each.

Question 2

Why does the O(1)O(1) amortized bound of the batched (two-list) queue fail when old versions are reused?

  1. The same expensive version can be operated on again and again, but its prepaid savings can be spent only once
  2. Immutable lists make every operation take Θ(n)\Theta(n)
  3. Reversing an immutable list takes Θ(n2)\Theta(n^2) time
  4. 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 nn such calls cost Θ(n2)\Theta(n^2).

Question 3

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?

  1. Nothing: delaying the reversal is enough
  2. The queue returns items in the wrong order
  3. Suspensions can never be forced
  4. 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.

Question 4

What does Okasaki's real-time queue guarantee that his banker's queue does not?

  1. Catenation of two queues in O(1)O(1)
  2. Persistence
  3. O(1)O(1) time for every operation in the worst case, not just amortized
  4. Freedom from lazy evaluation
Show the answer

C. O(1)O(1) time for every operation in the worst case, not just amortized

The banker's queue forces a whole reversal at once, Θ(n)\Theta(n) for that operation, though O(1)O(1) 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.