Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

Deamortization & Global Rebuilding

Turning amortized bounds into worst-case ones.

A hash table that doubles and rehashes is O(1)O(1) amortized per insert, yet one unlucky insert into a table of a hundred million keys stalls while every one of those keys is moved, far longer than any per-request deadline. For a game at 60 frames per second, a trading system or a pacemaker, that single stall is the whole story. Deamortization keeps the cheap average and removes the stall, by doing tomorrow's expensive work a little at a time today.

What you’ll learn

  • Explain when amortized bounds are not enough: latency, real-time systems and persistence.
  • Deamortize array and hash-table resizing by incremental copying, and prove that the copy always finishes in time.
  • Apply global and partial rebuilding, including scapegoat trees, and spread a rebuild over many operations.
  • Describe real-time queues and the known gaps between amortized and worst-case bounds, from union–find to strict Fibonacci heaps.

When the average is not enough

An amortized bound controls the total, and therefore the throughput, but not the latency of any one operation. Three situations make that difference decisive:

  • Real-time and interactive systems have a deadline per operation: a frame, a network packet, a control loop. A Θ(n)\Theta(n) pause misses it however rare it is.
  • Persistence: if old versions of a structure remain usable, an adversary can repeat an expensive operation on the same old version again and again. The credit stored for it is spent once and charged many times.
  • Concurrency: one thread stuck in a long resize can block every thread waiting on the same lock.

Deamortization turns an amortized bound f(n)f(n) into a worst-case bound O(f(n))O(f(n)) per operation. The universal trick is to schedule the expensive work: start it early and do a bounded piece of it during each cheap operation, so that it is finished by the time it is needed.

Incremental resizing

When a dynamic array of capacity CC fills up, allocate the new array of capacity 2C2C immediately, but do not copy yet. Each later append writes its element into the new array and also moves one or two old elements across. Reads look in the new array, or in the old one for elements not moved yet.

python
class IncrementalArray:
    """Append and index in O(1) worst-case time."""
    def __init__(self):
        self.cur, self.size = [None], 0    # current array, capacity len(self.cur)
        self.old, self.moved = None, 0     # array being emptied, elements moved so far

    def __getitem__(self, i):
        if self.old is not None and self.moved <= i < len(self.old):
            return self.old[i]             # not copied yet
        return self.cur[i]

    def append(self, x):
        if self.size == len(self.cur):     # full: switch arrays, copy lazily
            self.old, self.moved = self.cur, 0
            self.cur = [None] * (2 * len(self.old))
        self.cur[self.size] = x
        self.size += 1
        for _ in range(2):                 # move up to two old elements
            if self.old is not None:
                self.cur[self.moved] = self.old[self.moved]
                self.moved += 1
                if self.moved == len(self.old):
                    self.old = None        # copy finished

Over 100,000 appends this makes at most 3 element writes per append, against a single append that copies 65,536 elements in the doubling array: the same total work, 231,071 writes, but no spikes.

The same scheduling deamortizes hash tables: keep the old and the new table during a resize, look up keys in both, and migrate a few buckets of the old table during every operation. Redis's dictionaries resize this way, with incremental rehashing. And the memory overhead can be cut too: Brodnik, Carlsson, Demaine, Munro and Sedgewick (1999) gave resizable arrays with O(1)O(1) worst-case operations and only O(n)O(\sqrt n) wasted space, which they proved optimal.

Think first With doubling, why is one move per append exactly enough, and what happens if the array grows by a factor of 1.5 instead?

With doubling, CC moves must fit into the CC appends that fill the new array: one per append finishes just in time. With growth factor 1.5, the new array of capacity ⌈1.5C⌉\lceil1.5C\rceil has room for only about C/2C/2 more appends, so the CC moves need two per append (rounding the capacity down instead can force a third on small arrays). In general a growth factor gg needs at least 1/(g−1)1/(g-1) moves per append, and ⌈1/(g−1)⌉\lceil1/(g-1)\rceil suffice with capacities rounded up: a constant, as long as g>1g>1.

Global and partial rebuilding

Many structures degrade gracefully: they stay efficient while only a constant fraction of their contents is "out of shape". A balanced search tree with lazy deletion marks deleted nodes instead of removing them; searches step over them, and the height stays O(log⁡n)O(\log n) as long as at most half the nodes are marked. Global rebuilding (Overmars, 1983) exploits this: after εn\varepsilon n updates, throw the structure away and rebuild it from scratch. If a rebuild costs R(n)R(n), the amortized extra cost per update is O(R(n)/(εn))O\big(R(n)/(\varepsilon n)\big): O(1)O(1) for a linear-time rebuild, such as building a perfectly balanced tree from the sorted live keys.

Partial rebuilding rebuilds only the part that is out of shape. A scapegoat tree (Andersson, 1989; Galperin & Rivest, 1993) stores no balance information at all. When an insertion creates a node deeper than about log⁡1/αn\log_{1/\alpha}n, for a constant α\alpha between 12\tfrac12 and 1, some ancestor on its path is badly unbalanced, with a child holding more than an α\alpha fraction of its subtree. That ancestor is the scapegoat, and its subtree is rebuilt perfectly balanced in linear time. Searches take O(log⁡n)O(\log n) in the worst case, and updates O(log⁡n)O(\log n) amortized.

DerivationDeamortizing a global rebuild
  1. extra work per operation = O(R(n)εn)\text{extra work per operation}\ =\ O\Big(\frac{R(n)}{\varepsilon n}\Big)

    Start early. Begin the next rebuild while the current copy can still absorb a constant fraction of its tolerance. Build the new copy from a snapshot, spreading its R(n)R(n) steps over the next Θ(εn)\Theta(\varepsilon n) operations:

  2. bt+1 = bt+1−2 = bt−1b_{t+1}\ =\ b_t+1-2\ =\ b_t-1

    Catch up. Meanwhile the old copy keeps serving every operation, and the updates are also recorded in a buffer. Once the new copy is built, replay the buffer into it at two updates per operation: each operation adds one update to the buffer and removes two, so a buffer of bb updates empties within bb operations.

  3. worst case per operation = O(1+R(n)εn)\text{worst case per operation}\ =\ O\Big(1+\frac{R(n)}{\varepsilon n}\Big)

    Switch. When the buffer is empty, the new copy is up to date: discard the old one. With constants chosen so that the old copy never exceeds its tolerance before the switch, every operation does a bounded amount of work.

Check your understanding

A balanced search tree deletes lazily and rebuilds itself from its live keys, in O(n)O(n) time, whenever half of its nodes are marked deleted. What does this add per deletion?

  1. O(1)O(1) amortized
  2. O(log⁡n)O(\log n) amortized
  3. O(1)O(1) in the worst case
  4. O(n)O(n) amortized
Show the answer

A. O(1)O(1) amortized

A rebuild of a tree with nn nodes costs O(n)O(n) and happens only after about n/2n/2 deletions since the previous one, so each deletion pays O(1)O(1) toward it. A single deletion can still trigger the whole rebuild, so the bound is amortized, unless the rebuild is spread out as in the derivation above.

Queues, laziness and persistence

The classic two-stack queue pushes onto a back stack and pops from a front stack; when the front is empty, it pops the whole back stack onto the front, reversing it. Each element moves once, so operations are O(1)O(1) amortized, but one pop can cost Θ(n)\Theta(n). Worse, if versions are persistent, an old version with an empty front and a long back can be popped again and again, paying Θ(n)\Theta(n) every time: the amortized bound collapses.

Hood and Melville (1981) made the queue real-time: start the reversal early, when the back list grows longer than the front, and carry it out a constant number of steps per operation, so it is complete before the front runs out. Okasaki (1995) obtained the same O(1)O(1) worst-case bound far more simply with lazy evaluation: the reversal is a suspended computation, and an explicit schedule forces a constant amount of it during every operation.

Think first Okasaki also showed that lazy evaluation with memoization rescues amortized bounds under persistence. Why does memoization matter?

An expensive suspension, once forced, stores its result, and every version that shares the suspension reuses that result. Popping the same old version twice no longer redoes the reversal: the second time it is a lookup. The expensive work is paid once, as the amortized argument assumed, even though many versions may demand it.

Worst-case counterparts, and the gaps that remain

StructureAmortized boundWorst-case counterpart
dynamic arrayO(1)O(1) appendO(1)O(1) by incremental copying; O(n)O(\sqrt n) wasted space is optimal (Brodnik et al., 1999)
hash table with resizingO(1)O(1) expected amortizedincremental rehashing; de-amortized cuckoo hashing with O(1)O(1) worst-case operations with high probability (Arbitman, Naor & Segev, 2009)
binary counterO(1)O(1) incrementskew binary numbers: O(1)O(1) worst-case increment and decrement
Fibonacci heapO(1)O(1) insert and decrease-key, O(log⁡n)O(\log n) delete-minstrict Fibonacci heaps: the same bounds in the worst case, on a pointer machine (Brodal, Lagogiannis & Tarjan, 2012)
union–findO(α(n))O(\alpha(n)) per operationΘ(log⁡n/log⁡log⁡n)\Theta(\log n/\log\log n) per operation in the worst case, optimal for a broad class of algorithms (Blum, 1986)
splay treeO(log⁡n)O(\log n) per accessnone: self-adjustment is inherently amortized, and one access can take Θ(n)\Theta(n)

The union–find row is a real separation, not a missing idea. Blum's algorithm guarantees O(log⁡n/log⁡log⁡n)O(\log n/\log\log n) for every single operation, and he proved that no algorithm in a broad class, which includes the standard ones, does better per operation. Over a long sequence, path compression and union by rank average O(α(n))O(\alpha(n)), far less: an individual operation must sometimes be slow, but such operations are rare.

Key takeaways

  • Amortized bounds control throughput, not latency: real-time systems, persistence and concurrency need worst-case bounds per operation.
  • Deamortization schedules expensive work in advance, a bounded piece per operation. Incremental resizing gives arrays and hash tables O(1)O(1) worst-case updates, because the copy is guaranteed to finish before the next resize.
  • Global rebuilding restores a degraded structure from scratch every Θ(n)\Theta(n) updates, and can itself be spread out by building a new copy in the background and replaying a buffer; scapegoat trees rebuild only the subtree that is out of balance.
  • Persistence breaks amortized bounds by replaying expensive states; real-time queues (Hood & Melville; Okasaki) avoid them, and memoized laziness shares the expensive work instead of repeating it.
  • Some gaps are real: union–find is O(α(n))O(\alpha(n)) amortized but Θ(log⁡n/log⁡log⁡n)\Theta(\log n/\log\log n) worst case for broad classes, while Fibonacci heaps did get a worst-case twin in 2012.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A service inserts into a hash table that doubles and rehashes all keys when it gets too full. Its operators see rare latency spikes. What does deamortization change?

  1. It lowers the total work of all inserts
  2. It spreads each rehash over many later operations, so that every insert does O(1)O(1) work, at the price of keeping two tables during a resize
  3. It makes collisions less likely
  4. It avoids resizing altogether by allocating a huge table up front
Show the answer

B. It spreads each rehash over many later operations, so that every insert does O(1)O(1) work, at the price of keeping two tables during a resize

Incremental rehashing does the same total work, but in bounded pieces: lookups check both tables while the old one is being emptied. The spike disappears; the amortized cost does not change.

Question 2

An array doubles from capacity CC to 2C2C and copies its old elements incrementally, one per append. Why is the copy always finished before the next resize?

  1. Because copying is faster than appending
  2. Because reads also move elements
  3. Because the old array is freed immediately
  4. Because the next resize happens only when the new array is full, after CC more appends, and those appends move all CC old elements
Show the answer

D. Because the next resize happens only when the new array is full, after CC more appends, and those appends move all CC old elements

The new array has room for CC more elements, so the next resize is at least CC appends away, and CC appends move CC elements. Faster growth or slower copying would break the race; with growth factor gg, at least 1/(g−1)1/(g-1) moves per append are needed.

Question 3

Why does the two-stack queue lose its O(1)O(1) amortized bound when old versions remain usable?

  1. Because persistent structures cannot use stacks
  2. Because each version needs its own copy of every element
  3. Because an old version with an empty front stack can be popped repeatedly, and each pop repeats the Θ(n)\Theta(n) reversal
  4. Because enqueue becomes Θ(n)\Theta(n)
Show the answer

C. Because an old version with an empty front stack can be popped repeatedly, and each pop repeats the Θ(n)\Theta(n) reversal

The amortized argument pays for the reversal once, with credit from the pushes. Persistence lets the same expensive state be used many times, each time paying in full. Real-time queues avoid expensive states altogether, and memoized lazy evaluation makes the work shared instead of repeated.

Question 4

What is known about the per-operation cost of union–find?

  1. O(α(n))O(\alpha(n)) amortized, while for a broad class of algorithms the best worst case per operation is Θ(log⁡n/log⁡log⁡n)\Theta(\log n/\log\log n)
  2. Path compression and union by rank give O(α(n))O(\alpha(n)) in the worst case for every single operation
  3. O(1)O(1) worst case, by global rebuilding
  4. Θ(log⁡n)\Theta(\log n) amortized, and no better bound is possible
Show the answer

A. O(α(n))O(\alpha(n)) amortized, while for a broad class of algorithms the best worst case per operation is Θ(log⁡n/log⁡log⁡n)\Theta(\log n/\log\log n)

A single find with path compression can still traverse a long path; only the total is O(m α(n))O(m\,\alpha(n)). Blum (1986) gave O(log⁡n/log⁡log⁡n)O(\log n/\log\log n) per operation in the worst case and proved it optimal for a broad class of algorithms, so the amortized and worst-case optima differ.

Further reading

  • M. H. Overmars, The Design of Dynamic Data Structures (1983).
  • R. T. Hood & R. C. Melville, "Real-time queue operations in pure LISP," Information Processing Letters 13 (1981), 50–54.
  • C. Okasaki, "Simple and efficient purely functional queues and deques," Journal of Functional Programming 5(4) (1995), 583–592.
  • I. Galperin & R. L. Rivest, "Scapegoat trees," Proceedings of the 4th ACM-SIAM Symposium on Discrete Algorithms (1993), 165–174.
  • G. S. Brodal, G. Lagogiannis & R. E. Tarjan, "Strict Fibonacci heaps," Proceedings of STOC (2012), 1177–1184.