TExcelTAD
Home › Data Structures: Hashing, Search Trees, B-Trees & Union-Find › Chaining under Simple Uniform Hashing

Chaining under Simple Uniform Hashing

With chaining, the cost of a search is the length of one chain. In the worst case that is nn. 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 α\alpha elements on average, a successful one about 1+α/21 + \alpha/2), 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 mm slots, independently of where the other keys went. Equivalently, hh is a function chosen uniformly at random from all functions U→{0,…,m−1}U \to \{0, \ldots, m - 1\}, and the keys are distinct.

Write njn_j for the length of chain jj, so n0+n1+⋯+nm−1=nn_0 + n_1 + \cdots + n_{m-1} = n. Each of the nn keys lands in slot jj with probability 1/m1/m, so

E[nj]=nm=αfor every slot j.E[n_j] = \frac{n}{m} = \alpha \qquad \text{for every slot } j.

We count elements examined (key comparisons) and assume computing h(k)h(k) takes O(1)O(1) time.

Unsuccessful search

Theorem. Under simple uniform hashing, a search for a key kk that is not in the table examines α\alpha elements in expectation, so it takes Θ(1+α)\Theta(1 + \alpha) expected time.

Proof. The search computes h(k)h(k) and scans the whole chain h(k)h(k). The key kk is equally likely to hash to each slot, independently of the stored keys, so the expected length of the chain it scans is E[nh(k)]=αE[n_{h(k)}] = \alpha. Adding the O(1)O(1) for computing h(k)h(k) gives Θ(1+α)\Theta(1 + \alpha). The "1" matters: with α\alpha 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.

python · try it yourself
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 nn stored elements, and new elements are inserted at the head of their chain.

Theorem. Under these assumptions a successful search examines, in expectation,

1+α2−α2n1 + \frac{\alpha}{2} - \frac{\alpha}{2n}

elements, so it also takes Θ(1+α)\Theta(1 + \alpha) expected time.

Proof

Number the elements x1,…,xnx_1, \ldots, x_n in insertion order. Because each insertion goes to the head of its chain, the elements before xix_i in its chain are exactly those inserted after xix_i that hash to the same slot. A search for xix_i examines those and then xix_i itself.

For i<ji < j let XijX_{ij} be the indicator of the event h(xi)=h(xj)h(x_i) = h(x_j). Under simple uniform hashing Pr⁡[h(xi)=h(xj)]=1/m\Pr[h(x_i) = h(x_j)] = 1/m, so E[Xij]=1/mE[X_{ij}] = 1/m. The number of elements examined, averaged over the target, is

E[1n∑i=1n(1+∑j=i+1nXij)]=1n∑i=1n(1+∑j=i+1n1m)linearity of expectation=1+1nm∑i=1n(n−i)=1+1nm⋅n(n−1)2=1+n−12m=1+α2−α2n.\begin{aligned} E\left[\frac{1}{n} \sum_{i=1}^{n} \left(1 + \sum_{j=i+1}^{n} X_{ij}\right)\right] &= \frac{1}{n} \sum_{i=1}^{n} \left(1 + \sum_{j=i+1}^{n} \frac{1}{m}\right) && \text{linearity of expectation} \\ &= 1 + \frac{1}{nm} \sum_{i=1}^{n} (n - i) \\ &= 1 + \frac{1}{nm} \cdot \frac{n(n-1)}{2} \\ &= 1 + \frac{n - 1}{2m} = 1 + \frac{\alpha}{2} - \frac{\alpha}{2n}. \end{aligned}

Intuitively, the target sits in a chain with about α\alpha 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.

python · try it yourself
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, m=Θ(n)m = \Theta(n), then α=O(1)\alpha = O(1) and all dictionary operations take O(1)O(1) expected time: insertion O(1)O(1) worst case, deletion O(1)O(1) worst case with doubly linked chains, search O(1+α)=O(1)O(1 + \alpha) = O(1) expected. Tables keep m=Θ(n)m = \Theta(n) 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 hh there are keys that all collide: since ∣U∣\lvert U \rvert is much larger than mm, some slot receives at least ∣U∣/m\lvert U \rvert / m keys of the universe, and an adversary who knows hh can store only those. The program shows that for h(k)=k mod mh(k) = k \bmod m, where the keys 0,m,2m,…0, m, 2m, \ldots all land in slot 0.

python · try it yourself
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 hh: pick it at random, at run time, from a suitable family. That is universal hashing, and it recovers the 1+α1 + \alpha 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 n=mn = m under simple uniform hashing the expected maximum chain length is Θ(lg⁡n/lg⁡lg⁡n)\Theta(\lg n / \lg \lg n), the maximum load of balls into bins. So a typical search costs O(1)O(1), but some searches cost noticeably more.

One random bin per ball30 balls, 9 bins emptymax 630 binsLess loaded of two random bins30 balls, 4 bins emptymax 330 bins

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 n=300n = 300 keys in m=100m = 100 slots, how many elements does an unsuccessful search examine on average?

  1. 1
  2. 1.5
  3. 3
  4. 300

With α=3\alpha = 3 and large nn, about how many elements does a successful search examine on average (insertion at the head)?

  1. 1.5
  2. 2.5
  3. 3
  4. 4

Why can no fixed hash function guarantee short chains for every set of keys?

  1. Because mm is prime
  2. Because some slot receives at least ∣U∣/m\lvert U \rvert / m keys of the universe, and an adversary can store only those
  3. Because chaining needs linked lists
  4. It can: the division method does