Sub topic 13
When an amortised bound is not enough
This chapter assumes you can read short Python programs and know the earlier chapters' results. A doubling dynamic array has O(1) amortised append. A chained hash table that rehashes at a fixed load factor has O(1) amortised, expected-case insertion. Here you will see what those guarantees leave out, how to detect when that matters, and how to change a structure so the bad cases are bounded.
What an amortised bound promises
An amortised bound says that any sequence of n operations, starting from an empty structure, costs at most n times the amortised cost in total. It limits the sum. It says nothing about how that total is spread across individual operations.
Three things follow from this definition:
- A single operation can cost Θ(n), and the bound is still correct.
- The expensive operations can come at predictable moments, such as the append that fills the array. Nothing in the bound lets you move them elsewhere.
- The bound counts operations that are run in order on one version of the structure. If your usage breaks that assumption, the bound no longer applies.
Whether this is acceptable depends on who pays for the expensive operation and what happens when they do.
Seeing the spike
The simulation below charges 1 for each write and 1 for each element copied during a resize. It records the cost of every append, then compares the mean with the maximum.
def append_costs(n):
size, capacity = 0, 1
costs = []
for _ in range(n):
cost = 1 # write the new element
if size == capacity:
cost += size # copy every element into the larger array
capacity *= 2
size += 1
costs.append(cost)
return costs
for n in (1_000, 100_000, 1_000_000):
costs = append_costs(n)
mean = sum(costs) / n
assert mean < 3
print(n, round(mean, 2), max(costs))The mean stays below 3 for every n, which is the amortised result. The maximum grows with n. At n = 100,000 the worst append costs 65,537 units, because the array holds 65,536 elements when it fills. Both numbers are true. Which one matters depends on what you are building.
Where the average is the wrong number
Latency-sensitive code
A service that answers requests is judged by its slow requests, not its average ones. If one request in a million triggers a resize that takes 200 ms, the mean latency barely moves but the 99.99th percentile does. The same applies to:
- Audio and video callbacks that must finish within a fixed deadline.
- Game loops with a frame budget of about 16 ms.
- Real-time control systems, where a missed deadline is a failure and not a slow response.
- Trading or network code with strict tail-latency targets.
In these systems the relevant bound is the worst case for each operation, or a high percentile. Amortised analysis cannot give you that.
Locks and shared state
If a resize runs while a thread holds a lock, every other thread waits for the whole copy. The pause is paid by unrelated callers, who did not cause it and cannot see it coming. A single slow append in a shared queue can stall a pipeline that is otherwise idle.
Memory spikes
Doubling needs the old array and the new array at the same time. Growing from n slots to 2n slots needs 3n slots at the peak. A process that is comfortable at n slots can run out of memory during the resize. The amortised time bound says nothing about this peak.
Reusing an expensive state
The potential and accounting arguments assume operations run in sequence and each state is used once. If you can return to a saved state and operate on it again, an adversary can pick the costly state every time. This happens with persistent (immutable) versions of a structure, with undo and redo stacks, and with backtracking search that copies a structure and extends each copy.
The model below tracks only size and capacity, and charges the same costs as before. It applies the same append to one full state repeatedly.
def append_state(size, capacity):
"""Return (new_size, new_capacity, cost) for one append."""
cost = 1
if size == capacity:
cost += size
capacity *= 2
return size + 1, capacity, cost
full = (1024, 1024) # a full array: the next append must resize
total = 0
branches = 1000
for _ in range(branches):
_, _, cost = append_state(*full) # each branch starts from the same saved state
total += cost
assert total == branches * 1025
print(total / branches) # 1025 per append, not a small constantEach branch pays the full resize, because none of them benefits from the cheap appends that would normally follow it. The amortised guarantee is for a single timeline. If your design lets callers fork the state, you need worst-case bounds or a structure designed for persistence.
Hash tables and the "expected" part
The chapter on expected versus amortised cost showed that hash table insertion has two separate averages. The amortised part covers resizing and holds for every input sequence. The expected part covers chain lengths and holds only if the hash function spreads keys well. If an attacker can choose keys that collide, the expected bound fails and a single bucket can hold most of the table. Resizing does not help, because the colliding keys stay together after rehashing. Defences such as randomised or keyed hash functions address this, and amortised analysis does not.
De-amortising: turning a total bound into a per-operation bound
You cannot make the total work smaller. You can make each operation do a small piece of the work. This is de-amortisation: the expensive step is split into small steps, spread over the operations that follow it.
For a hash table, this is incremental rehashing. When the load factor is exceeded, allocate the new bucket array but keep the old one. Each later operation moves a few buckets from old to new. Lookups check both tables until the migration finishes.
class IncrementalTable:
MAX_LOAD = 0.75
BUCKETS_PER_STEP = 2
def __init__(self):
self._old = None
self._new = [[] for _ in range(8)]
self._cursor = 0
self._size = 0
self.max_work = 0 # largest cost of any single put
def _migrate(self):
moved = 0
steps = 0
while self._old is not None and steps < self.BUCKETS_PER_STEP:
bucket = self._old[self._cursor]
for k, v in bucket:
self._new[hash(k) % len(self._new)].append((k, v))
moved += 1
bucket.clear()
self._cursor += 1
steps += 1
if self._cursor == len(self._old):
self._old = None
return moved
def _put(self, key, value):
work = 1
if self._old is not None:
work += self._migrate()
if self._old is not None:
bucket = self._old[hash(key) % len(self._old)]
for i, (k, _) in enumerate(bucket):
work += 1
if k == key:
bucket[i] = (key, value)
return work
bucket = self._new[hash(key) % len(self._new)]
for i, (k, _) in enumerate(bucket):
work += 1
if k == key:
bucket[i] = (key, value)
return work
bucket.append((key, value))
self._size += 1
if self._old is None and self._size > self.MAX_LOAD * len(self._new):
self._old = self._new
self._new = [[] for _ in range(2 * len(self._old))]
self._cursor = 0
return work
def put(self, key, value):
self.max_work = max(self.max_work, self._put(key, value))
def get(self, key, default=None):
for table in (self._new, self._old):
if table is None:
continue
for k, v in table[hash(key) % len(table)]:
if k == key:
return v
return default
table = IncrementalTable()
for i in range(100_000):
table.put(i, i * i)
assert table.get(31337) == 31337 * 31337
assert table.max_work <= 8 # no put ever rehashes the whole table
print(table.max_work)Two details make this work:
- The migration rate must outpace the growth. An old table with m buckets needs m / 2 operations at two buckets per step. The next resize needs 0.75m more insertions, so migration always finishes first. At one bucket per step it would not.
- Writes go to the new table, and updates to the old table stay in place. A key that is still in an unmigrated old bucket is updated there, so it is never duplicated.
The total work is unchanged, and it is slightly higher because of the double lookups. You are buying a bounded worst case with a constant-factor cost and more complex code.
Choosing an approach
| Approach | Worst-case cost of one operation | Cost you accept |
|---|---|---|
| Plain doubling or rehash | Θ(n) | Occasional long pause, 3n peak memory |
| Reserve capacity up front | O(1) until capacity is exceeded | You must know or bound n |
| Incremental resizing | O(1) expected per operation | Both tables live during migration, lookups check two places, more complex code |
| Chunked or tree-based structure | O(log n) or O(1) | Slower indexing and worse cache behaviour than one flat array |
Reserving capacity is the cheapest fix when it applies. It removes the resizes entirely, and most standard libraries expose it, for example reserve on C++ vectors or a size hint when creating a Java ArrayList or Go slice.
Measuring instead of assuming
Before you de-amortise anything, check that the spike matters:
- Record the latency of each operation, not only the total time.
- Look at the maximum and the high percentiles, not the mean.
- Compare them against the requirement. If the worst append is far below your deadline, the amortised bound is enough, and extra machinery only adds bugs.
Summary of the limits
- Amortised bounds cap the total, not the individual operation.
- They assume operations run in order on one timeline, so forking or reusing a saved state breaks them.
- They do not cover peak memory, lock hold times, or adversarial hashing.
- Remedies are to reserve capacity, to spread the work with incremental resizing, or to choose a structure whose worst case is bounded.
Exercise
A logging service appends records to a shared dynamic array under a mutex. The mean append time is 80 ns, but once every few minutes all producer threads stall for about 300 ms. Explain the cause using this chapter's ideas, and give two different fixes with one cost for each.
Show answer
The stall is a resize. The append that fills the array copies every element while holding the mutex, so all other threads wait for the full copy. The mean stays low because the amortised bound covers only the total. Fix 1: reserve enough capacity at startup, or double-buffer so writers append to a small fresh buffer and a background thread merges it. The cost is that you must estimate the maximum size, or you pay extra memory and complexity. Fix 2: use a chunked structure, for example a list of fixed-size blocks, so growth allocates one new block and copies nothing. The cost is slower indexing and worse cache locality than a flat array.
Exercise
In the IncrementalTable, suppose BUCKETSPERSTEP were 1 instead of 2. The old table has m buckets and a resize starts when size exceeds 0.75m. Why can the design fail, and what happens to the invariant that only one old table exists?
Show answer
Migrating the old table takes m operations at one bucket per step. The next resize triggers when size exceeds 0.75 times the new bucket count, which is 1.5m, so it needs about 0.75m more insertions. Migration is then unfinished when the next resize should begin. The code only starts a resize when self._old is None, so growth is delayed and the load factor of the new table climbs above 0.75, which lengthens chains and breaks the O(1) expected cost. The migration rate must be at least the growth rate, so two buckets per step is the smallest integer that works here.