Sub topic 7
Primary clustering and why it hurts
This chapter assumes you know linear probing from the previous chapter, Python lists and loops, and average versus worst-case Big-O.
What a cluster is
With linear probing, a key that finds its home slot taken tries the next slot, then the next. Over time, occupied slots form unbroken runs. Each run is called a cluster. Primary clustering is the tendency of those runs to grow and merge.
The cause is a feedback loop. A new key lands in a cluster if its home slot is anywhere inside the run. It then probes to the run's end and extends the run by one slot. A longer run covers more home slots, so it is more likely to catch the next key.
Why it hurts
Slots in a cluster do not need a collision with your key's own hash. They only need to sit between your home slot and the end of the run. So the cost of a lookup depends on the length of the cluster you fall into, not on how many keys share your hash value.
Two operations suffer most:
- Inserts and unsuccessful lookups. They must walk to the end of the run, because only an empty slot proves the key is absent.
- Anything near a high load factor. Clusters merge, and a few long runs dominate the table.
Knuth's classic analysis gives the expected number of probes for linear probing at load factor α:
| Load factor α | Successful lookup | Unsuccessful lookup or insert |
|---|---|---|
| 0.5 | 1.5 | 2.5 |
| 0.7 | 2.2 | 6.1 |
| 0.9 | 5.5 | 50.5 |
The formulas are ½(1 + 1/(1−α)) for success and ½(1 + 1/(1−α)²) for failure. The squared term explains the sharp rise near full.
Seeing it in code
This simulation inserts random keys, modelled as random home slots, into a table with linear probing. It reports the average probes per insert and the longest run.
import random
def longest_run(used):
best = run = 0
for flag in used + used: # doubled so runs that wrap around are counted
run = run + 1 if flag else 0
best = max(best, run)
return min(best, len(used))
def simulate(capacity, n_keys, seed=0):
rng = random.Random(seed)
used = [False] * capacity
total_probes = 0
for _ in range(n_keys):
i = rng.randrange(capacity)
probes = 1
while used[i]:
i = (i + 1) % capacity
probes += 1
used[i] = True
total_probes += probes
return total_probes / n_keys, longest_run(used)
for load in (0.5, 0.7, 0.9):
avg, longest = simulate(1000, int(1000 * load))
print(f"load {load:.1f}: avg probes {avg:.2f}, longest cluster {longest}")Exact numbers depend on the seed. The pattern should not: both the average and the longest cluster rise faster than the load does. The average here covers every insert from an empty table, so it is lower than the table above, which describes an insert made at that load.
Reducing the effect
The probe sequence is the problem. Every key that starts in a run follows the same path out of it. The next two chapters change the sequence:
- Quadratic probing jumps by growing offsets, so keys in the same run diverge.
- Double hashing derives the step from a second hash, so even keys with the same home slot diverge.
Neither removes clustering entirely. Quadratic probing still makes keys with the same home slot share one path, which is called secondary clustering. The simplest defence is also the cheapest: resize before the load factor climbs high. Many linear-probing tables resize at around 0.5 to 0.75.
Exercise
A linear-probing table has 10 slots. Slots 2 through 6 are occupied and the rest are empty. If a new key's home slot is chosen uniformly at random, what is the probability that the insert lands in slot 7, and why does that make the cluster grow?
Show answer
Slot 7 is chosen whenever the home slot is any of 2, 3, 4, 5, or 6, so the probability is 5/10 = 50%. Each of those home slots is occupied, so the key probes forward to the first free slot, which is 7. The cluster then covers slots 2 through 7 and catches even more home slots next time.