Deamortization & Global Rebuilding
Turning amortized bounds into worst-case ones.
A hash table that doubles and rehashes is 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 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 into a worst-case bound 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 fills up, allocate the new array of capacity 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.
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 finishedOver 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 worst-case operations and only 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, moves must fit into the appends that fill the new array: one per append finishes just in time. With growth factor 1.5, the new array of capacity has room for only about more appends, so the moves need two per append (rounding the capacity down instead can force a third on small arrays). In general a growth factor needs at least moves per append, and suffice with capacities rounded up: a constant, as long as .
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 as long as at most half the nodes are marked. Global rebuilding (Overmars, 1983) exploits this: after updates, throw the structure away and rebuild it from scratch. If a rebuild costs , the amortized extra cost per update is : 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 , for a constant between and 1, some ancestor on its path is badly unbalanced, with a child holding more than an fraction of its subtree. That ancestor is the scapegoat, and its subtree is rebuilt perfectly balanced in linear time. Searches take in the worst case, and updates amortized.
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 steps over the next operations:
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 updates empties within operations.
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.
A balanced search tree deletes lazily and rebuilds itself from its live keys, in time, whenever half of its nodes are marked deleted. What does this add per deletion?
- amortized
- amortized
- in the worst case
- amortized
Show the answer
A. amortized
A rebuild of a tree with nodes costs and happens only after about deletions since the previous one, so each deletion pays 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 amortized, but one pop can cost . Worse, if versions are persistent, an old version with an empty front and a long back can be popped again and again, paying 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 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
| Structure | Amortized bound | Worst-case counterpart |
|---|---|---|
| dynamic array | append | by incremental copying; wasted space is optimal (Brodnik et al., 1999) |
| hash table with resizing | expected amortized | incremental rehashing; de-amortized cuckoo hashing with worst-case operations with high probability (Arbitman, Naor & Segev, 2009) |
| binary counter | increment | skew binary numbers: worst-case increment and decrement |
| Fibonacci heap | insert and decrease-key, delete-min | strict Fibonacci heaps: the same bounds in the worst case, on a pointer machine (Brodal, Lagogiannis & Tarjan, 2012) |
| union–find | per operation | per operation in the worst case, optimal for a broad class of algorithms (Blum, 1986) |
| splay tree | per access | none: self-adjustment is inherently amortized, and one access can take |
The union–find row is a real separation, not a missing idea. Blum's algorithm guarantees 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 , 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 worst-case updates, because the copy is guaranteed to finish before the next resize.
- Global rebuilding restores a degraded structure from scratch every 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 amortized but 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.
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?
- It lowers the total work of all inserts
- It spreads each rehash over many later operations, so that every insert does work, at the price of keeping two tables during a resize
- It makes collisions less likely
- 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 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.
An array doubles from capacity to and copies its old elements incrementally, one per append. Why is the copy always finished before the next resize?
- Because copying is faster than appending
- Because reads also move elements
- Because the old array is freed immediately
- Because the next resize happens only when the new array is full, after more appends, and those appends move all old elements
Show the answer
D. Because the next resize happens only when the new array is full, after more appends, and those appends move all old elements
The new array has room for more elements, so the next resize is at least appends away, and appends move elements. Faster growth or slower copying would break the race; with growth factor , at least moves per append are needed.
Why does the two-stack queue lose its amortized bound when old versions remain usable?
- Because persistent structures cannot use stacks
- Because each version needs its own copy of every element
- Because an old version with an empty front stack can be popped repeatedly, and each pop repeats the reversal
- Because enqueue becomes
Show the answer
C. Because an old version with an empty front stack can be popped repeatedly, and each pop repeats the 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.
What is known about the per-operation cost of union–find?
- amortized, while for a broad class of algorithms the best worst case per operation is
- Path compression and union by rank give in the worst case for every single operation
- worst case, by global rebuilding
- amortized, and no better bound is possible
Show the answer
A. amortized, while for a broad class of algorithms the best worst case per operation is
A single find with path compression can still traverse a long path; only the total is . Blum (1986) gave 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.