Chaining under Simple Uniform Hashing
With chaining, the cost of a search is the length of one chain. In the worst case that is . To say anything better we need an assumption about how the hash function spreads the keys, and the cleanest one is that it behaves like a random function. This lesson states that assumption, proves the two classic results (an unsuccessful search examines elements on average, a successful one about ), and checks both by simulation.
The proofs are short applications of indicator random variables, the tool used for randomized quicksort in the previous course.
The model
Simple uniform hashing (an idealization, not a property of any fixed function): each key is equally likely to hash to any of the slots, independently of where the other keys went. Equivalently, is a function chosen uniformly at random from all functions , and the keys are distinct.
Write for the length of chain , so . Each of the keys lands in slot with probability , so
We count elements examined (key comparisons) and assume computing takes time.
Unsuccessful search
Theorem. Under simple uniform hashing, a search for a key that is not in the table examines elements in expectation, so it takes expected time.
Proof. The search computes and scans the whole chain . The key is equally likely to hash to each slot, independently of the stored keys, so the expected length of the chain it scans is . Adding the for computing gives . The "1" matters: with tiny, the search still has to hash the key.
The program builds many tables with random hash values (the model, simulated directly) and measures the average chain length scanned by searches for absent keys.
import random
rng = random.Random(42)
m, trials = 101, 800
print(f"{'alpha':>6} {'measured':>9} {'theory':>7}")
for n in [50, 101, 202, 404]:
total = 0
for _ in range(trials):
lengths = [0] * m
for _ in range(n):
lengths[rng.randrange(m)] += 1 # a stored key lands in a random slot
total += lengths[rng.randrange(m)] # the absent key's chain is scanned fully
print(f"{n / m:>6.2f} {total / trials:>9.3f} {n / m:>7.3f}") alpha measured theory
0.50 0.515 0.495
1.00 0.963 1.000
2.00 2.007 2.000
4.00 3.947 4.000
Successful search
For a successful search the question is which element we search for. Take the standard assumption: the target is equally likely to be any of the stored elements, and new elements are inserted at the head of their chain.
Theorem. Under these assumptions a successful search examines, in expectation,
elements, so it also takes expected time.
Proof
Number the elements in insertion order. Because each insertion goes to the head of its chain, the elements before in its chain are exactly those inserted after that hash to the same slot. A search for examines those and then itself.
For let be the indicator of the event . Under simple uniform hashing , so . The number of elements examined, averaged over the target, is
Intuitively, the target sits in a chain with about other elements, and on average half of them come before it. The simulation inserts at the head of each chain and averages over every stored element.
import random
rng = random.Random(7)
m, trials = 64, 300
print(f"{'n':>4} {'alpha':>6} {'measured':>9} {'1 + (n-1)/(2m)':>15}")
for n in [16, 64, 128, 256, 512]:
total = 0
for _ in range(trials):
chains = [[] for _ in range(m)]
for i in range(n):
chains[rng.randrange(m)].insert(0, i) # insert at the head
# searching for the element at position p of its chain examines p + 1 elements
total += sum(p + 1 for chain in chains for p in range(len(chain)))
print(f"{n:>4} {n / m:>6.2f} {total / (trials * n):>9.3f} {1 + (n - 1) / (2 * m):>15.3f}") n alpha measured 1 + (n-1)/(2m)
16 0.25 1.121 1.117
64 1.00 1.496 1.492
128 2.00 1.993 1.992
256 4.00 2.992 2.992
512 8.00 4.991 4.992
What the theorems say, and what they do not
If the number of slots is proportional to the number of keys, , then and all dictionary operations take expected time: insertion worst case, deletion worst case with doubly linked chains, search expected. Tables keep by rehashing as they grow (Hash Tables with Chaining).
The expectation is over the hash function, under an assumption no fixed function can satisfy. For any fixed there are keys that all collide: since is much larger than , some slot receives at least keys of the universe, and an adversary who knows can store only those. The program shows that for , where the keys all land in slot 0.
m, n = 1000, 1000
def h(k):
return k % m
friendly = range(n) # consecutive keys
hostile = range(0, n * m, m) # multiples of m
for name, keys in [("consecutive keys", friendly), ("multiples of m", hostile)]:
lengths = [0] * m
for k in keys:
lengths[h(k)] += 1
work = sum(L * (L + 1) // 2 for L in lengths) # all successful searches
print(f"{name:17}: longest chain {max(lengths):4}, average successful search {work / n:6.1f} comparisons")consecutive keys : longest chain 1, average successful search 1.0 comparisons
multiples of m : longest chain 1000, average successful search 500.5 comparisons
The way out is to stop letting the adversary know : pick it at random, at run time, from a suitable family. That is universal hashing, and it recovers the bound for every set of keys, with a proof that does not rely on the idealized model. In practice, hash tables exposed to untrusted input (web servers parsing request parameters, for example) do exactly that, using a seeded hash function.
Note: The longest chain is a different question from the average. With under simple uniform hashing the expected maximum chain length is , the maximum load of balls into bins. So a typical search costs , but some searches cost noticeably more.
In the lab, n is the number of slots and m the number of keys (the lab's own names). The left panel is chaining with one random slot per key: run 1 ends with a longest chain of 6, although the average chain has length 1. The right panel is a variation, putting each key in the shorter of two random chains, which keeps the longest chain at 3; the balls-into-bins lesson explains why.
Test yourself
Under simple uniform hashing with keys in slots, how many elements does an unsuccessful search examine on average?
- 1
- 1.5
- 3
- 300
With and large , about how many elements does a successful search examine on average (insertion at the head)?
- 1.5
- 2.5
- 3
- 4
Why can no fixed hash function guarantee short chains for every set of keys?
- Because is prime
- Because some slot receives at least keys of the universe, and an adversary can store only those
- Because chaining needs linked lists
- It can: the division method does