Sub topic 10
Expected versus amortised: two different averages
This chapter assumes you know Big-O notation, how a chained hash table stores keys in buckets, and the doubling resize from the earlier chapters. It also assumes you can read short Python programs.
"Average cost" can mean two different things. Hash table documentation often says "O(1) average insertion" while a dynamic array says "O(1) amortised append". Both claims are about averages, but they rest on different foundations, they fail in different ways, and they can be combined. This chapter separates them.
What each average is taken over
An expected cost is an average over randomness. Some source of chance (random input, a randomly chosen hash function) makes the cost of one operation a random variable. The expected cost is its mean. It holds for each operation, in the sense that if you repeat the experiment many times, the mean is the stated bound.
An amortised cost is an average over a sequence of operations. No randomness is involved. You fix any sequence of n operations, add up their real costs, and divide by n. The bound holds for every sequence, including one chosen by an adversary who knows your code.
| Row | Expected cost | Amortised cost |
|---|---|---|
| Averaged over | Random choices | Operations in one sequence |
| Needs an assumption about input or hashing | Yes | No |
| Can one operation be much larger than the bound | Yes, with small probability | Yes, with certainty at some point |
| Holds against an adversary | Only if the randomness is hidden from them | Yes |
| Typical example | Lookup in a chained hash table | Append to a doubling array |
The two guarantees in a hash table insert
Inserting into a resizing chained hash table involves both kinds of average at once, and they cover different parts of the cost.
- Finding the bucket and scanning its chain. The cost is proportional to the chain length. If the hash function spreads keys uniformly, the expected chain length is the load factor α, which resizing keeps at or below 0.75. This part is an expected O(1) bound.
- Resizing. When the load factor passes the threshold, every entry moves to a new bucket array. A single insert can cost Θ(n). Because the bucket count doubles, the total number of moves across n inserts is below about 2n, whatever the keys are. This part is an amortised O(1) bound.
Together, the insert is described as O(1) amortised in expectation. The word "amortised" covers the resize. The words "in expectation" cover the chain scan. Neither bound implies the other.
Seeing the two bounds separate
The program below inserts the same number of keys into a chained table twice. In the first run the keys have well-spread hash values. In the second run every key has hash value 0, so all keys land in one bucket. It counts two things: key comparisons while scanning chains, and entry moves during resizing.
import random
class Key:
"""A key whose hash value we control, so we can simulate a bad hash."""
def __init__(self, value, hash_value):
self.value = value
self.hash_value = hash_value
def __hash__(self):
return self.hash_value
def __eq__(self, other):
return self.value == other.value
class CountingTable:
MAX_LOAD = 0.75
def __init__(self):
self.buckets = [[] for _ in range(8)]
self.size = 0
self.compares = 0 # work done scanning chains
self.moves = 0 # work done during resizing
def put(self, key):
bucket = self.buckets[hash(key) % len(self.buckets)]
for existing in bucket:
self.compares += 1
if existing == key:
return
bucket.append(key)
self.size += 1
if self.size > self.MAX_LOAD * len(self.buckets):
self._grow()
def _grow(self):
new_buckets = [[] for _ in range(2 * len(self.buckets))]
for bucket in self.buckets:
for key in bucket:
new_buckets[hash(key) % len(new_buckets)].append(key)
self.moves += 1
self.buckets = new_buckets
def run(n, make_hash):
table = CountingTable()
for i in range(n):
table.put(Key(i, make_hash(i)))
return table
n = 2000
rng = random.Random(1)
good = run(n, lambda i: rng.getrandbits(32))
bad = run(n, lambda i: 0)
print("good hash: compares", good.compares, "moves", good.moves)
print("bad hash: compares", bad.compares, "moves", bad.moves)
assert good.moves == bad.moves # resize work depends only on the count
assert bad.moves < 3 * n # amortised bound holds for any keys
assert bad.compares == n * (n - 1) // 2 # chain scans become quadratic overallThe moves counts are identical in both runs. Resizing is triggered by the number of entries, not by where they hash, so its total cost is bounded for any key sequence. That is the amortised guarantee at work.
The compares counts differ enormously. With the bad hash, the i-th insert scans i existing keys, so n inserts cost n(n−1)/2 comparisons. That is Θ(n) per insert on average, and amortisation cannot repair it. The "expected O(1)" bound depended on the hash function spreading keys, and that assumption failed.
Why the expected bound needs an assumption
The standard result for chained hashing is that, if each key is equally likely to land in any bucket and independently of other keys, the expected chain length is α. An unsuccessful search then costs about 1 + α expected steps. With α ≤ 0.75, that is a constant.
The assumption can be met in two ways:
- Random keys. You assume the data itself is random. This is fragile, because real keys such as sequential IDs, timestamps, or user-chosen names are rarely uniform.
- A random hash function. The table picks its hash function at random from a family (a universal family) when it is created. The expectation is then over that choice, and it holds for every fixed key set. This is the sound way to get the bound, and the reason many languages randomise string hashing per process.
Notice that the randomisation only works if an attacker cannot see the chosen function. If the seed leaks, or the hash is a fixed public function, someone can craft keys that all collide. This is the idea behind hash-flooding attacks on web servers that parse request parameters into hash tables.
Why the amortised bound needs no assumption
The amortised bound for the resize is a statement about the worst possible sequence. The aggregate argument from earlier chapters did not look at the keys. It only used the fact that a resize at size s is followed by at least s/2 inserts before the next resize, with each resize costing s moves. So total moves are below 2n for any inserts.
The price is that the bound is about totals. It says nothing about any single call. One insert in a million will take about a million steps, and that is guaranteed to happen, not merely likely.
Comparing the failure modes
| Situation | Expected bound | Amortised bound |
|---|---|---|
| Adversary picks keys that collide | Fails | Unaffected for resizing |
| Adversary picks the worst operation order | Unaffected if the hash is hidden | Unaffected |
| You care about the slowest single call | Slow calls are rare but possible | The slow call certainly happens |
| You care about total time for a batch | Fine, if the assumption holds | Fine |
The last two rows matter in practice. If you process a batch of a million inserts and only care about total time, both bounds give you what you need. If each insert serves a user request with a latency budget, a guaranteed spike at a resize is a different problem from a rare spike caused by a bad collision streak. The final chapters return to this.
Common mistakes
- Treating "average case" and "amortised" as synonyms. Average-case analysis needs a probability model of the input. Amortised analysis needs none.
- Claiming a hash table is "O(1) amortised" with no further qualification. Without the hash assumption, a chained table can degrade to O(n) per operation. State both parts: amortised for resizing, expected for chain length.
- Thinking expected cost removes spikes. A random hash function makes long chains unlikely. It does nothing about the full rehash, which is a deterministic spike.
- Averaging expected and amortised bounds incorrectly. The two multiply or add as separate cost terms. You do not get a stronger bound by combining them. You get a statement that needs both assumptions.
Putting it together
When you meet a claimed average cost, ask three questions:
- What is the average taken over: a random choice, or a sequence of operations?
- What must be true for the claim to hold? For expected bounds, what is assumed about hashing or input? For amortised bounds, the only requirement is that the analysis covers the full sequence from an empty structure.
- What does it say about a single operation? Usually, nothing useful.
For a dynamic array, only the second kind of average appears. For a chained hash table, both appear, and keeping them separate is what lets you say exactly which part of the guarantee a bad hash function breaks and which part it leaves alone.
Exercise
In the program above, a table with the constant hash function 0 performs exactly the same number of entry moves as a table with well-spread hashes, yet is far slower overall. Which kind of average explains why the move count is the same, which kind explains why the comparison count is not, and what change to the table would restore an O(1) expected bound for chain scans?
Show answer
The move count is bounded by the amortised argument. Resizes are triggered by the number of entries only, so total moves are below about 2n for any keys, and both runs give the same number. The comparison count depends on chain lengths, which are bounded only in expectation and only if the hash spreads keys. With a constant hash the assumption fails, and the n inserts cost n(n-1)/2 comparisons. To restore the expected bound, use a hash function that spreads keys, for example one chosen at random from a universal family when the table is created, so that the expectation is over that choice for every fixed key set.