---
title: "Hash Tables"
book: "University Computer Science — Year 1"
subject: computer-science
language: en
chapter: 16
exercises: 12
source: https://one-course.com/books/computer-science/3/en/chapter/16-hash-tables
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 16 — Hash Tables

A directory of a million names, sorted alphabetically, finds any name in about twenty looks: binary search halves the candidates each time, and $2^{20}$ is a million. Twenty is good; one would be better. If a name could be turned directly into the position where it is stored, one look would suffice. A [hash table](#def-b1-hash-tables-hash-table) does this: a function computes a position from the key, and the table deals with the [keys](#def-b1-hash-tables-dictionary) that land on the same position. Its expected cost per operation is constant, under an assumption about the [keys](#def-b1-hash-tables-dictionary) that an adversary can break, which this chapter also shows, with the defence.

**You already know.**

A [dynamic array](https://one-course.com/books/computer-science/3/en/chapter/14-dynamic-arrays-and-amortised-analysis#def-b1-dynamic-arrays-dynamic-array) that doubles when full has amortised constant cost per insertion ([Chapter 14](https://one-course.com/books/computer-science/3/en/chapter/14-dynamic-arrays-and-amortised-analysis#ch-b1-dynamic-arrays)). A [singly linked list](https://one-course.com/books/computer-science/3/en/chapter/15-linked-structures-lists-stacks-and-queues#def-b1-linked-structures-list) inserts and removes at a known link in constant time ([Chapter 15](https://one-course.com/books/computer-science/3/en/chapter/15-linked-structures-lists-stacks-and-queues#ch-b1-linked-structures)). Unsigned integer arithmetic in C is exact modulo $2^{64}$ for `uint64_t` ([Chapter 2](https://one-course.com/books/computer-science/3/en/chapter/2-c-types-operators-and-control-flow#ch-b1-c-types-and-control)).

## 16.1 Dictionaries and sets

**Definition 16.1 (Dictionary, key).**

A *dictionary* is an abstract type that associates values with *keys*, each key at most once, with the operations insert (or replace) the value of a key, search for the value of a key, and delete a key. A *set* is a dictionary without values.

The structures of the previous chapters already implement it. A list of pairs searches in $\Theta(n)$; a sorted [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) searches in $\Theta(\log n)$ but inserts in $\Theta(n)$. Python’s `dict` and `set`, used since the first programming chapters, are [hash tables](#def-b1-hash-tables-hash-table); this chapter builds two in C.

## 16.2 Hash functions

**Definition 16.2 (Hash function, hash value).**

A *hash function* maps every key to an integer, its *hash value*; equal [keys](#def-b1-hash-tables-dictionary) must have equal hash values. For a table of $m$ positions, the position of a key is its hash value modulo $m$.

For integer [keys](#def-b1-hash-tables-dictionary), the *division method* takes $k \bmod m$, with $m$ a prime far from a power of 2. For strings, four functions show what makes a hash good: the first character only; the sum of the characters (the additive hash); the polynomial $s_0 31^{L-1} + s_1 31^{L-2} + \dots + s_{L-1} \bmod 2^{64}$, evaluated by Horner’s scheme; and FNV-1a, which mixes in each byte with an exclusive or and multiplies by a fixed prime, $2^{40} + 2^8 + 179$, starting from a fixed offset basis.

```c
uint64_t hash_additive(const char *s) {
    uint64_t h = 0;
    for (; *s; s++) h += (unsigned char)*s;
    return h;
}

uint64_t hash_poly(const char *s) {
    uint64_t h = 0;
    for (; *s; s++) h = 31 * h + (unsigned char)*s;  // Horner's scheme
    return h;
}

uint64_t hash_fnv1a_seeded(const char *s, uint64_t seed) {
    uint64_t h = 14695981039346656037u ^ seed;  // the offset basis
    for (; *s; s++) {
        h ^= (unsigned char)*s;  // first mix in the byte,
        h *= 1099511628211u;     // then multiply by the FNV prime
    }
    return h;
}
```

***Listing 16.1.** The additive, polynomial and FNV-1a [hash functions](#def-b1-hash-tables-hash-function) code/bachelor-1/16-hash-tables/listings/hashes.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o hash_funcs hash_funcs.c hashes.c -lm && ./hash_funcs
key               first    sum             polynomial                 FNV-1a
Emil Thornworth      69   1510    4823985697052263020   11054835887681660221
Quinn Woodwell       81   1400    6703446872864427958   11443257886469045911
listen              108    655             3192458695   15891737647324053542
silent              115    655             3392640085    6452236368899434340
Aa                   65    162                   2112     650843846546077079
BB                   66    132                   2112     653890593267282085

buckets, m = 31 (the hash value mod 31):
Emil Thornworth       7     22                      9                     16
Quinn Woodwell       19      5                     21                     26
listen               15      4                     17                     22
silent               22      4                     23                     15
Aa                    3      7                      4                      1
BB                    4      8                      4                     22
```

***Output 16.1.** Four [hash values](#def-b1-hash-tables-hash-function) of six [keys](#def-b1-hash-tables-dictionary), then their positions among 31.*

The first character ignores the rest of the key. The additive hash gives the same value to `listen` and `silent`, and to every reordering of a word. The polynomial hash distinguishes orders, but `Aa` and `BB` collide: $65 \cdot 31 + 97 = 66 \cdot 31 + 66 = 2112$. With $m = 31$, the polynomial hash of a short key keeps only its last character, since every other term is a multiple of 31 (`listen` lands in [bucket](#def-b1-hash-tables-hash-table) $110 \bmod 31 = 17$, the [bucket](#def-b1-hash-tables-hash-table) of its `n`); only the wrap modulo $2^{64}$ of longer [keys](#def-b1-hash-tables-dictionary) disturbs this. The multiplier and the table size must not share a factor. A good [hash function](#def-b1-hash-tables-hash-function) spreads the [keys](#def-b1-hash-tables-dictionary) that occur in practice evenly over the positions, and is fast.

## 16.3 Chaining

**Definition 16.3 (Hash table, bucket, collision).**

A *hash table* stores a [dictionary](#def-b1-hash-tables-dictionary) in an [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) of $m$ *buckets*; the key $k$ belongs to bucket $h(k) \bmod m$. Two different [keys](#def-b1-hash-tables-dictionary) in the same bucket form a *collision*.

**Definition 16.4 (Separate chaining, open addressing, linear probing, tombstone).**

In *separate chaining*, each [bucket](#def-b1-hash-tables-hash-table) holds a [linked list](https://one-course.com/books/computer-science/3/en/chapter/15-linked-structures-lists-stacks-and-queues#def-b1-linked-structures-list) of the entries that belong to it. In *open addressing*, all entries live in the [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) itself, and a key whose position is taken goes to another position, computed by a fixed rule; with *linear probing*, the next position, cyclically. A deletion in open addressing leaves a *tombstone*: a mark that the slot is free for an insertion but that a search must go past.

**Definition 16.5 (Load factor, rehashing).**

The *load factor* of a table holding $n$ [keys](#def-b1-hash-tables-dictionary) in $m$ [buckets](#def-b1-hash-tables-hash-table) is $\alpha = n/m$. *Rehashing* moves every entry to a new [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) of a different size, recomputing its position.

![Keys, a hash function and seven buckets with chaining: dog and saw land in the same bucket, which then holds a list of two entries. Empty buckets hold null pointers. (Illustrative positions.)](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-hash-tables/fig-e61b0070bba1.svg)

*[Keys](#def-b1-hash-tables-dictionary), a [hash function](#def-b1-hash-tables-hash-function) and seven [buckets](#def-b1-hash-tables-hash-table) with chaining: `dog` and `saw` land in the same [bucket](#def-b1-hash-tables-hash-table), which then holds a list of two entries. Empty [buckets](#def-b1-hash-tables-hash-table) hold [null pointers](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-null). (Illustrative positions.)*

```c
static entry **find(chain *t, const char *key) {  // the link to the key's cell, or to NULL
    entry **link = &t->buckets[t->h(key) % t->m];
    while (*link != NULL) {
        t->compared++;
        if (strcmp((*link)->key, key) == 0) break;
        link = &(*link)->next;
    }
    return link;
}
```

***Listing 16.2.** Finding a key in its chain: the link to its cell, or to the end of the chain code/bachelor-1/16-hash-tables/listings/chain.c*

The function `find` returns a [pointer](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer) to the link that leads to the key’s cell, as the removal of [Chapter 15](https://one-course.com/books/computer-science/3/en/chapter/15-linked-structures-lists-stacks-and-queues#ch-b1-linked-structures) did; insertion, search and deletion all use it. With resizing on, the table doubles its [buckets](#def-b1-hash-tables-hash-table) when $n > m$, which keeps $\alpha \leq 1$.

```
$ gcc -std=c17 -O2 -Wall -Wextra -o chain_demo chain_demo.c chain.c hashes.c -lm && ./chain_demo
the    5
cat    2
dog    2
river  1
fish   0
8 keys in 7 buckets, chain lengths: 1 2 2 0 0 2 1
after deleting "the": 7 keys
```

***Output 16.2.** Counting the words of a sentence with the [dictionary](#def-b1-hash-tables-dictionary).*

A search costs the hash, plus one key comparison per entry of the chain examined. In the worst case every key falls into one [bucket](#def-b1-hash-tables-hash-table), and a search costs $\Theta(n)$. The average case needs an assumption on the [keys](#def-b1-hash-tables-dictionary).

**Definition 16.6 (Simple uniform hashing).**

The assumption of *simple uniform hashing* is that each key is equally likely to fall into any of the $m$ [buckets](#def-b1-hash-tables-hash-table), independently of the other [keys](#def-b1-hash-tables-dictionary).

Under this assumption, a chain holds $\alpha$ [keys](#def-b1-hash-tables-dictionary) on average, an unsuccessful search compares $\alpha$ [keys](#def-b1-hash-tables-dictionary) and a successful one about $1 + \alpha/2$, so that with $m$ proportional to $n$ every operation has constant expected cost. The proof needs expectations of random variables, and belongs to the second year; the counts below check it.

![A cloakroom works like separate chaining: the ticket names a hook, a hook may hold several coats, and the attendant looks through the few coats of one hook, never through the whole room.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-hash-tables/img-a9e91546fc6a.jpg)

*A cloakroom works like [separate chaining](#def-b1-hash-tables-collisions): the ticket names a hook, a hook may hold several coats, and the attendant looks through the few coats of one hook, never through the whole room.*

## 16.4 Open addressing

[Open addressing](#def-b1-hash-tables-collisions) avoids the lists and their [pointers](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer): the [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) holds the entries, and a key whose slot is taken probes the next slots until it finds its own key or a free slot. The search stops at a free slot, because the key would have been placed there.

```c
// the slot holding key, or else the first reusable slot met (tombstone or free)
static size_t find(probe *t, const char *key, bool *found) {
    size_t i = t->h(key) % t->m, reusable = t->m;
    for (size_t step = 0; step < t->m; step++, i = (i + 1) % t->m) {
        t->probes++;
        slot *s = &t->slots[i];
        if (s->state == FREE) break;  // the key is not further on
        if (s->state == DEAD) {
            if (reusable == t->m) reusable = i;
        } else if (strcmp(s->key, key) == 0) {
            *found = true;
            return i;
        }
    }
    *found = false;
    return reusable < t->m ? reusable : i;
}
```

***Listing 16.3.** Searching with [linear probing](#def-b1-hash-tables-collisions), past [tombstones](#def-b1-hash-tables-collisions) code/bachelor-1/16-hash-tables/listings/probe.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o probe_demo probe_demo.c probe.c hashes.c -lm && ./probe_demo
put Ada  (hash  65 mod 11 = 10)  ..........A
put Bo   (hash  66 mod 11 =  0)  B.........A
put Lea  (hash  76 mod 11 = 10)  BL........A
put Al   (hash  65 mod 11 = 10)  BLA.......A
put Cy   (hash  67 mod 11 =  1)  BLAC......A
put Bea  (hash  66 mod 11 =  0)  BLACB.....A
put Wes  (hash  87 mod 11 = 10)  BLACBW....A
delete Bo                         xLACBW....A
get Bea: found, value 5, 5 probes
```

***Output 16.3.** Seven [keys](#def-b1-hash-tables-dictionary) hashed by their first letter into 11 slots: a cluster forms; a deletion leaves a [tombstone](#def-b1-hash-tables-collisions) `x`.*

Deleting `Bo` by marking its slot free would break the search for `Bea`, which starts at slot 0 and would stop there; the [tombstone](#def-b1-hash-tables-collisions) keeps the chain of probes intact, and a later insertion can reuse it. The demonstration also shows the weakness of [linear probing](#def-b1-hash-tables-collisions): occupied slots form *clusters*, runs of consecutive slots, which any key hashing into them lengthens. The expected number of probes, under uniform hashing, is about $\frac12(1 + \frac{1}{1 - \alpha})$ for a successful search and $\frac12(1 + \frac{1}{(1 - \alpha)^2})$ for an unsuccessful one, so the table must stay well below full; this one doubles when [keys](#def-b1-hash-tables-dictionary) and [tombstones](#def-b1-hash-tables-collisions) fill three quarters of it.

![Linear probing after the demonstration: Ada sits in slot 10, the others that hash to 10 wrapped to slots 1, 2 and 5, and the deleted Bo left a tombstone in slot 0. Marking slot 0 free instead would end the search for Bea at once.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-hash-tables/fig-0e3098aeaf97.svg)

*[Linear probing](#def-b1-hash-tables-collisions) after the demonstration: Ada sits in slot 10, the others that hash to 10 wrapped to slots 1, 2 and 5, and the deleted Bo left a [tombstone](#def-b1-hash-tables-collisions) in slot 0. Marking slot 0 free instead would end the search for Bea at once.*

The counts of the two designs, as the [load factor](#def-b1-hash-tables-load-factor) grows, come from a simulation with random positions:

![Keys compared (chaining) and slots probed (linear probing) per search, counted on a table of 10 007 buckets filled with random positions. Chaining degrades gently; probing stays cheap up to about = 0.7, then explodes for absent keys (46 probes at 0.9, 123 at 0.95, off the chart).](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-hash-tables/fig-0ee99b4a98f9.svg)

*[Keys](#def-b1-hash-tables-dictionary) compared (chaining) and slots probed ([linear probing](#def-b1-hash-tables-collisions)) per search, counted on a table of 10 007 [buckets](#def-b1-hash-tables-hash-table) filled with random positions. Chaining degrades gently; probing stays cheap up to about $\alpha = 0.7$, then explodes for absent [keys](#def-b1-hash-tables-dictionary) (46 probes at 0.9, 123 at 0.95, off the chart).*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o timing timing.c chain.c probe.c hashes.c -lm && ./timing
alpha   chaining    probing   (ns per search)
 0.25       12.6       17.1
 0.50       15.5       24.4
 0.75       18.3       36.3
 0.90       17.1       57.4
 0.95       18.9       90.4
```

***Output 16.4.** Searches timed on the author’s laptop, $m =
2^{16}$.*

Here chaining wins at every [load factor](#def-b1-hash-tables-load-factor). Probing touches consecutive slots of one [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array), which suits the memory hierarchy, but each slot of this table holds a [pointer](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer) to its key, so every probe also follows a [pointer](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-pointer) to compare the key, and the advantage of the contiguous [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) is lost; near a full table the long clusters add the rest. Tables that store short [keys](#def-b1-hash-tables-dictionary), such as integers, in the slots themselves are where probing is fastest.

## 16.5 Resizing, and inputs that defeat a hash function

A table that doubles its size when the [load factor](#def-b1-hash-tables-load-factor) passes a threshold rehashes every key, at a cost proportional to the number of [keys](#def-b1-hash-tables-dictionary); as for the [dynamic array](https://one-course.com/books/computer-science/3/en/chapter/14-dynamic-arrays-and-amortised-analysis#def-b1-dynamic-arrays-dynamic-array), the total over $n$ insertions is $O(n)$, an amortised constant per insertion ([Exercise 16.10](#exo-b1-hash-tables-10)).

```
       n      moves    moves/n    slots
    1000       1538      1.538     2048
   10000      12293      1.229    16384
  100000     196617      1.966   262144
 1000000    1572876      1.573  2097152
a real table holds 1000 keys, 1000 found again
```

***Output 16.5.** [Keys](#def-b1-hash-tables-dictionary) moved by the rehashes of $n$ insertions, doubling at load $\frac34$. Some lines are left out.*

The expected constant cost rests on the assumption that the [keys](#def-b1-hash-tables-dictionary) spread evenly. [Keys](#def-b1-hash-tables-dictionary) chosen by an adversary need not. Under the additive hash, every reordering of a word lands in the same [bucket](#def-b1-hash-tables-hash-table); under the polynomial hash, the blocks `Aa` and `BB` can be combined into $2^k$ strings of length $2k$ with one [hash value](#def-b1-hash-tables-hash-function). A server that stores the names of the fields of a request in a [hash table](#def-b1-hash-tables-hash-table) can be sent thousands of such names, and spend quadratic time on one request.

```
$ gcc -std=c17 -O2 -Wall -Wextra -o attack attack.c hashes.c -lm && ./attack
AaAaAaAaAaAaAaAaAaAa BBAaAaAaAaAaAaAaAaAa ... BBBBBBBBBBBBBBBBBBBB
1024 keys, 1024 with the polynomial hash 1694101504502301312
FNV-1a, seed 0: 655 of 1021 buckets used; the first key in bucket 385
FNV-1a, seed 1: 653 of 1021 buckets used; the first key in bucket 769
FNV-1a, seed 2: 645 of 1021 buckets used; the first key in bucket 811
```

***Output 16.6.** 1024 strings built from `Aa` and `BB`: one polynomial [hash value](#def-b1-hash-tables-hash-function); FNV-1a with three seeds spreads them, differently each time.*

The defence is a [hash function](#def-b1-hash-tables-hash-function) with a secret: a seed chosen at random when the program starts, mixed into the hash, so that an attacker cannot know which [keys](#def-b1-hash-tables-dictionary) collide. Python has done this for strings for many years, and since version 3.4 uses SipHash, a function designed to resist such attacks, for `str` and `bytes`.

**In practice.**

In Python, `hash("abc")` changes from one run of the [interpreter](https://one-course.com/books/computer-science/3/en/chapter/1-from-source-code-to-a-running-program#def-b1-compilation-pipeline-interpreter) to the next, unless `PYTHONHASHSEED` fixes the seed — which the captures of this book do, so that their outputs repeat. Never store such [hash values](#def-b1-hash-tables-hash-function) in a file or send them to another program: they are only meaningful inside one run.

## 16.6 Exercises

**Exercise 16.1 ★.**

With the division method and $m = 11$, give the [bucket](#def-b1-hash-tables-hash-table) of the [keys](#def-b1-hash-tables-dictionary) 15, 26, 37, 100 and 121. Which collide?

**Solution of Exercise 16.1.**

[Buckets](#def-b1-hash-tables-hash-table) 4, 4, 4, 1 and 0: 15, 26 and 37 collide (they differ by multiples of 11).

**Exercise 16.2 ★.**

Insert the [keys](#def-b1-hash-tables-dictionary) 18, 41, 22, 44, 59, 32, 31, 73 in this order into a table of 13 slots with $h(k) = k \bmod 13$ and [linear probing](#def-b1-hash-tables-collisions). Draw the table.

**Solution of Exercise 16.2.**

18 goes to 5, 41 to 2, 22 to 9; 44 (home 5) to 6; 59 to 7; 32 (home 6) probes 6, 7 and lands in 8; 31 (home 5) probes 5 to 9 and lands in 10; 73 (home 8) probes 8, 9, 10 and lands in 11. Slots 0 to 12: `- - 41 - - 18 44 59 32 22 31 73 -`. The run from slot 5 to slot 11 is one cluster of seven.

**Exercise 16.3 ★.**

Five [keys](#def-b1-hash-tables-dictionary) have additive [hash values](#def-b1-hash-tables-hash-function) 300, 310, 320, 331 and 341, and $m = 10$. Give the chain lengths with chaining.

**Solution of Exercise 16.3.**

The [buckets](#def-b1-hash-tables-hash-table) are 0, 0, 0, 1 and 1: chains of length 3 and 2, and eight empty [buckets](#def-b1-hash-tables-hash-table).

**Exercise 16.4 ★.**

A chaining table of 16 [buckets](#def-b1-hash-tables-hash-table) doubles when $n > m$. What are $m$ and $\alpha$ after 17, 33 and 100 insertions?

**Solution of Exercise 16.4.**

After 17 insertions, $m = 32$ and $\alpha = 17/32 \approx 0.53$; after 33, $m = 64$, $\alpha \approx 0.52$; after 100 (the 65th doubled again), $m = 128$, $\alpha \approx 0.78$.

**Exercise 16.5 ★★.**

This deletion marks the slot free. Explain the output, and repair the deletion.

```c
enum { M = 7, EMPTY = -1 };
int slot[M] = {EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY};

void put(int key) {
    int i = key % M;
    while (slot[i] != EMPTY) i = (i + 1) % M;
    slot[i] = key;
}

int find(int key) {  // the slot of key, or -1
    for (int i = key % M; slot[i] != EMPTY; i = (i + 1) % M)
        if (slot[i] == key) return i;
    return -1;
}

void delete(int key) {
    int i = find(key);
    if (i >= 0) slot[i] = EMPTY;
}

int main(void) {
    put(10), put(17), put(24), put(5);  // 10, 17 and 24 all hash to 3
    delete(17);
    printf("find(24) = %d, find(5) = %d, find(10) = %d\n", find(24), find(5), find(10));
    return 0;
}
```

***Listing 16.4.** Insertion, search and deletion code/bachelor-1/16-hash-tables/listings/exo_delete_bug.c*

```
find(24) = -1, find(5) = 6, find(10) = 3
```

***Output 16.7.** After deleting 17. Some lines are left out.*

**Solution of Exercise 16.5.**

10, 17 and 24 all have home slot 3; they sit in slots 3, 4 and 5, and 5 (home 5) went to slot 6. Deleting 17 frees slot 4, and the search for 24, starting at 3, stops at the free slot 4: 24 is lost although it is still in slot 5. The search for 5 starts at 5 and is not affected. The repair marks the slot with a [tombstone](#def-b1-hash-tables-collisions) (a third value, say `-2`) that `find` skips and `put` may reuse, as [Listing 16.3](#lst-b1-hash-tables-probe) does.

**Exercise 16.6 ★★.**

A colleague hashes names by their first character only. Read the first row of the problem’s table ([Output 16.8](#out-b1-hash-tables-town)): why does the longest chain stay 9 whatever $m$, and why do 101 of 127 [buckets](#def-b1-hash-tables-hash-table) stay empty? What does [linear probing](#def-b1-hash-tables-collisions) cost with it?

**Solution of Exercise 16.6.**

The first characters are capital letters, at most 26 values, which stay distinct modulo any $m \geq 26$: the longest chain is the number of people sharing the commonest initial, 9, whatever $m$, and only the 26 [buckets](#def-b1-hash-tables-hash-table) of the initials used can be occupied, so $127 - 26 = 101$ stay empty. With [linear probing](#def-b1-hash-tables-collisions) the 26 home slots are close together, their clusters merge into one long run, and a search costs about 50 probes, as the table shows.

**Exercise 16.7 ★★.**

Write a set of non-negative integers by [open addressing](#def-b1-hash-tables-collisions) with [linear probing](#def-b1-hash-tables-collisions) (no deletion), doubling when three quarters full, and test it against an [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) of booleans.

**Solution of Exercise 16.7.**

```c
static size_t home(long x, size_t m) {  // multiply by a large odd constant, then reduce
    return (size_t)((unsigned long)x * 11400714819323198485u % m);
}

bool intset_init(intset *s) {  // false when out of memory
    s->m = 8, s->n = 0;
    s->slot = malloc(s->m * sizeof *s->slot);
    if (s->slot == NULL) return false;
    for (size_t i = 0; i < s->m; i++) s->slot[i] = -1;
    return true;
}

bool intset_has(const intset *s, long x) {
    for (size_t i = home(x, s->m); s->slot[i] != -1; i = (i + 1) % s->m)
        if (s->slot[i] == x) return true;
    return false;
}

static void place(long *slot, size_t m, long x) {
    size_t i = home(x, m);
    while (slot[i] != -1) i = (i + 1) % m;
    slot[i] = x;
}

bool intset_add(intset *s, long x) {  // precondition: x >= 0; false when out of memory
    if (intset_has(s, x)) return true;
    if (4 * (s->n + 1) > 3 * s->m) {  // rehash into twice as many slots
        long *bigger = malloc(2 * s->m * sizeof *bigger);
        if (bigger == NULL) return false;  // the set is left as it was
        for (size_t i = 0; i < 2 * s->m; i++) bigger[i] = -1;
        for (size_t i = 0; i < s->m; i++)
            if (s->slot[i] != -1) place(bigger, 2 * s->m, s->slot[i]);
        free(s->slot);
        s->slot = bigger, s->m *= 2;
    }
    place(s->slot, s->m, x);
    s->n++;
    return true;
}
```

*A set of integers by [linear probing](#def-b1-hash-tables-collisions) code/bachelor-1/16-hash-tables/exercises/intset.c*

The home slot multiplies the key by a large odd constant before taking it modulo $m$, which spreads consecutive integers. Before an insertion that would pass three quarters, every key is placed again in an [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) twice as large. The test adds 50 000 random values below 100 000 and checks every value against an [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) of booleans, and the load after every insertion.

**Exercise 16.8 ★★.**

Write a program that reads a text and prints the frequency of each word with the chaining table, and check it against Python’s `collections.Counter`.

**Solution of Exercise 16.8.**

`exercises/wordfreq.c` reads characters, lowers the letters of each word, and calls `chain_get` then `chain_put` with the count plus one; a second [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array) remembers the order of first appearance for the printing. The Python test compiles it with `chain.c`, runs it on a text, and compares the result with `Counter(words)` for the same split of the text into words.

**Exercise 16.9 ★★.**

Show that if all $n$ [keys](#def-b1-hash-tables-dictionary) fall into one [bucket](#def-b1-hash-tables-hash-table), there are $n(n - 1)/2$ colliding pairs, and that if they are spread as evenly as possible over $m$ [buckets](#def-b1-hash-tables-hash-table), there are about $n^2/(2m)$.

**Solution of Exercise 16.9.**

A [bucket](#def-b1-hash-tables-hash-table) of $\ell$ [keys](#def-b1-hash-tables-dictionary) holds $\binom{\ell}{2}$ colliding pairs. One [bucket](#def-b1-hash-tables-hash-table) of $n$: $n(n - 1)/2$. Evenly, $m$ [buckets](#def-b1-hash-tables-hash-table) of $n/m$: $m \cdot \frac{(n/m)(n/m - 1)}{2} = \frac{n(n - m)}{2m} \approx \frac{n^2}{2m}$ when $m \ll n$, and about $m$ times fewer pairs.

**Exercise 16.10 ★★★.**

A table starts with 8 slots and, after an insertion that makes $n > \frac34 m$, doubles and rehashes its $n$ [keys](#def-b1-hash-tables-dictionary). Prove that $n$ insertions move fewer than $2n + \log_2 n$ [keys](#def-b1-hash-tables-dictionary) in all, that the number of moves per insertion comes close to 2 just after a doubling, and compare with [Output 16.5](#out-b1-hash-tables-resize).

**Solution of Exercise 16.10.**

The doublings happen from $m_0 = 8$, $m_1 = 16$, …, $m_j = 8 \cdot 2^j$ slots, each when the table holds $\frac34 m_i +
1$ [keys](#def-b1-hash-tables-dictionary), which it moves. In all: $\sum_{i=0}^{j} (\frac34 m_i + 1) = \frac34 (2m_j - 8) + j + 1 = \frac32 m_j + j - 5$. The last doubling happened at or before the $n$-th insertion, so $\frac34 m_j + 1 \leq n$, that is $\frac32 m_j \leq 2n -
2$, and $j = \log_2 (m_j/8) < \log_2 n$: the moves total at most $2n + j - 7 < 2n + \log_2 n$. Right after a doubling, $n = \frac34 m_j + 1$ and the total is $2n + j - 7$, so the ratio is close to 2; it falls to about 1 just before the next doubling, when $n \approx \frac32 m_j$ insertions have shared the same $\frac32 m_j$ moves. The output shows 1.966 at $n = 100\,000$, just past the doubling at 98 305 [keys](#def-b1-hash-tables-dictionary), and 1.229 at $n = 10\,000$, long after the one at 6145. Amortised, a rehash costs a constant per insertion.

**Exercise 16.11 ★★★.**

Write `colliding(k, L)`, which returns $k$ distinct strings of length $L$ with the same value of $h(s) = \sum_i s_i
31^{L-1-i} \bmod 2^{64}$, and test it. Prove that it works.

**Solution of Exercise 16.11.**

```python
def colliding(k, length):
    """k distinct strings of the even length `length`, all with one hash value."""
    blocks = length // 2
    assert length % 2 == 0 and k <= 2**blocks
    return ["".join(p) for p in islice(product(["Aa", "BB"], repeat=blocks), k)]
```

*Strings made of equal-hash blocks code/bachelor-1/16-hash-tables/exercises/collide.py*

Split $s$ into $L/2$ blocks of two characters: $h(s) = \sum_j v_j\, 31^{L - 2 - 2j} \bmod 2^{64}$ with $v_j = 31 s_{2j} +
s_{2j+1}$ the value of block $j$. Both `Aa` and `BB` have value 2112, so every string made of such blocks has the same sum, as an integer and so modulo $2^{64}$; there are $2^{L/2}$ of them. The test checks 1000 strings of length 20.

**Exercise 16.12 ★★★.**

Prove that under the additive hash every permutation of a word has the same [hash value](#def-b1-hash-tables-hash-function). Among the $26^4$ words of four letters `a` to `z`, how many share the most common additive [hash value](#def-b1-hash-tables-hash-function)? Count it with a program, and explain why it is the middle value.

**Solution of Exercise 16.12.**

Addition is commutative: the sum of the characters does not depend on their order. Over the $26^4 = 456\,976$ words of four letters, the sums run from $4 \cdot 97 = 388$ to $4 \cdot 122 = 488$, 101 values, and the most common, 438, is shared by 11 726 words (`exercises/additive_count.py`, tested). The distribution of a sum of four independent uniform letters is symmetric about its mean $4 \cdot 109.5 = 438$ and increases up to it: the number of ways to write a sum grows while every letter still has room on both sides.

## 16.7 Problem: Collisions in the town directory

**Problem 16.1.**

Weekend problem — Collisions in the town directory

The 120 people of the town are keyed by their full name, read from the town’s `people.csv`. A program stores them in tables of 31, 64 and 127 [buckets](#def-b1-hash-tables-hash-table) with chaining, and of 127 and 251 slots with [linear probing](#def-b1-hash-tables-collisions), under the four [hash functions](#def-b1-hash-tables-hash-function), and reports the longest chain, the empty [buckets](#def-b1-hash-tables-hash-table), and the average cost of a successful search. A second program hashes the 720 orders of the letters of one word.

```
$ gcc -std=c17 -O2 -Wall -Wextra -o chains_town chains_town.c chain.c probe.c hashes.c -lm && ./chains_town
chaining: longest chain / empty buckets / keys compared per successful search
                     m = 31          m = 64         m = 127
first           9   5   3.29     9  38   3.29     9 101   3.29
additive       10   0   2.96     5   9   1.90     4  53   1.48
polynomial     18   2   4.55     5   9   1.91     3  43   1.37
FNV-1a         10   0   2.92     7   4   1.89     4  51   1.47
linear probing: slots probed per successful search
              m = 127   m = 251
first           49.65     49.65
additive         9.31      1.80
polynomial       4.34      1.51
FNV-1a           7.17      1.42
```

***Output 16.8.** The town’s names under four [hash functions](#def-b1-hash-tables-hash-function).*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o anagrams anagrams.c hashes.c -lm && ./anagrams
additive   720 keys in   1 buckets, largest bucket 720
polynomial 720 keys in 127 buckets, largest bucket  12
```

***Output 16.9.** The 720 orders of six distinct letters, in 127 [buckets](#def-b1-hash-tables-hash-table).*

**Part I — Four hash functions.**

1. With 120 [keys](#def-b1-hash-tables-dictionary) and $m = 31$ , what is the smallest possible longest chain? Which functions come close?
2. Explain the polynomial hash’s longest chain of 18 at $m = 31$ , and why it drops at $m = 64$ and 127.
3. Why does the first-character hash give the same longest chain for every $m \geq 26$ ?
4. On these names the additive hash does about as well as FNV-1a. Why is it nevertheless a poor general [hash function](#def-b1-hash-tables-hash-function) ? (Think of short [keys](#def-b1-hash-tables-dictionary) , and of [Exercise 16.12](#exo-b1-hash-tables-12) .)
5. Which of the four would you choose, and why?
6. Why must equal [keys](#def-b1-hash-tables-dictionary) have equal [hash values](#def-b1-hash-tables-hash-function) , but unequal [keys](#def-b1-hash-tables-dictionary) need not have unequal ones?

**Part II — Chaining.**

7. For FNV-1a, compare the [keys](#def-b1-hash-tables-dictionary) compared per successful search with $1 + \alpha/2$ for the three values of $m$ .
8. With 120 [keys](#def-b1-hash-tables-dictionary) in 127 [buckets](#def-b1-hash-tables-hash-table) , about how many [buckets](#def-b1-hash-tables-hash-table) should stay empty under uniform hashing? Compare with the table.
9. Prove that the average number of [keys](#def-b1-hash-tables-dictionary) compared per successful search is $\frac1n \sum_b \frac{\ell_b(\ell_b + 1)}{2}$ , where $\ell_b$ is the length of chain $b$ ( [keys](#def-b1-hash-tables-dictionary) added at the end of their chain).
10. Deduce that, for fixed $n$ and $m$ , this average is smallest when the chains are as equal as possible.
11. What does a search for an absent key cost, in the worst case and on average?
12. Why does the table of the problem not resize?

**Part III — Open addressing.**

13. Compute $\alpha$ for 127 and 251 slots, and compare the FNV-1a probes with $\frac12(1 + \frac{1}{1 - \alpha})$ .
14. Why does the first-character hash cost about 50 probes per search, whatever the table size?
15. Explain why a cluster grows faster the longer it is.
16. Why does probing need $m > n$ , while chaining works with $m < n$ ?
17. Why can a search stop at a free slot but not at a [tombstone](#def-b1-hash-tables-collisions) ?
18. When the table is resized, what happens to the [tombstones](#def-b1-hash-tables-collisions) ?

**Part IV — An attacker’s names.**

19. Prove that, under the additive hash, a set of $k$ distinct letters gives $k!$ [keys](#def-b1-hash-tables-dictionary) in one [bucket](#def-b1-hash-tables-hash-table) .
20. Read [Output 16.9](#out-b1-hash-tables-anagrams) : how many [buckets](#def-b1-hash-tables-hash-table) do the 720 [keys](#def-b1-hash-tables-dictionary) use under each hash?
21. With $n$ [keys](#def-b1-hash-tables-dictionary) in one [bucket](#def-b1-hash-tables-hash-table) , what does inserting all of them cost with chaining? And with a hash that spreads them over $m \geq n$ [buckets](#def-b1-hash-tables-hash-table) ?
22. An attacker knows the polynomial hash. How many names of length 20 with one [hash value](#def-b1-hash-tables-hash-function) can he build from `Aa` and `BB` ( [Output 16.6](#out-b1-hash-tables-attack) )?
23. Why does a random seed defeat that attack, and why must the seed stay secret?
24. State the named result of the problem, *the anagram attack* , with its proof and the numbers printed.

**Solution of Problem 16.1.**

**1.** $\lceil 120/31 \rceil = 4$. None reaches it: the first letter gives 9 (with 5 empty [buckets](#def-b1-hash-tables-hash-table)), the additive hash and FNV-1a 10, the polynomial 18; random positions typically give a longest chain of 8 or 9, so these are ordinary.

**2.** Modulo 31, every term $s_i 31^{L-1-i}$ but the last is 0: for a name short enough not to wrap modulo $2^{64}$, the [bucket](#def-b1-hash-tables-hash-table) is its last character modulo 31. Eighteen names end in `y`, and $121 \bmod 31 = 28$: fifteen of them, the short ones, fill [bucket](#def-b1-hash-tables-hash-table) 28, and three longer names, whose hash wrapped, land there by chance: 18. For $m = 64$ or 127 the multiplier 31 is invertible modulo $m$ and every character counts.

**3.** At most 26 initials, distinct modulo $m \geq 26$ ([Exercise 16.6](#exo-b1-hash-tables-6)).

**4.** It ignores the order of the characters, so anagrams always collide (question 19), and short [keys](#def-b1-hash-tables-dictionary) have sums in a narrow range: the $26^4$ words of four letters take only 101 values, so a table of a thousand [buckets](#def-b1-hash-tables-hash-table) would use at most 101 of them.

**5.** FNV-1a: it uses every byte, mixes them, and has no relation with any $m$; the polynomial hash is as good when $m$ is coprime with 31.

**6.** A search looks only in the key’s [bucket](#def-b1-hash-tables-hash-table), so equal [keys](#def-b1-hash-tables-dictionary) must meet there. Unequal [keys](#def-b1-hash-tables-dictionary) cannot all have different values: there are infinitely many strings and finitely many [hash values](#def-b1-hash-tables-hash-function).

**7.** $\alpha = 3.87, 1.875, 0.945$ give $1 + \alpha/2 = 2.94, 1.94, 1.47$; the table shows 2.92, 1.89, 1.47.

**8.** $127(1 - \frac{1}{127})^{120} \approx 127 e^{-0.945} \approx 49$. The table shows 51 for FNV-1a, 53 and 43 for the others.

**9.** The key in position $j$ of its chain costs $j$ comparisons; a chain of $\ell_b$ [keys](#def-b1-hash-tables-dictionary) costs $1 + \dots +
\ell_b$ in all; divide by $n$.

**10.** If two chains have lengths $\ell_1 \geq \ell_2 + 2$, moving a key from the first to the second changes the sum by $(\ell_2 + 1) - \ell_1 < 0$: the minimum has all lengths within one of each other.

**11.** The whole chain: $n$ in the worst case, $\alpha$ on average under uniform hashing.

**12.** To compare the [hash functions](#def-b1-hash-tables-hash-function) at fixed $m$; a resizing table would change $m$ during the experiment.

**13.** $\alpha = 0.945$ and $0.478$; the formula gives 9.6 and 1.46, the measurement 7.17 and 1.42.

**14.** The 26 home slots form one long cluster holding the 120 [keys](#def-b1-hash-tables-dictionary); a key sits on average about half a cluster from its home.

**15.** A key whose home is any slot of the cluster, or the free slot right after it, ends at the end of the cluster: a cluster of length $c$ grows with probability about $(c + 1)/m$, and long clusters also merge.

**16.** Every key occupies its own slot of the [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array).

**17.** A free slot was free when every key now present was inserted, so no probe sequence ever passed it; a [tombstone](#def-b1-hash-tables-collisions) was occupied, and a later key may have gone past it.

**18.** They disappear: only the live entries are inserted into the new [array](https://one-course.com/books/computer-science/3/en/chapter/4-pointers-and-arrays#def-b1-pointers-and-arrays-array).

**19.** The additive hash is invariant under permutation, and $k$ distinct letters have $k!$ distinct orders: $k!$ different [keys](#def-b1-hash-tables-dictionary), one [hash value](#def-b1-hash-tables-hash-function), one [bucket](#def-b1-hash-tables-hash-table).

**20.** 1 [bucket](#def-b1-hash-tables-hash-table) for the additive hash; all 127 for the polynomial, the largest holding 12 [keys](#def-b1-hash-tables-dictionary).

**21.** In one chain, the $i$-th insertion first searches the $i - 1$ [keys](#def-b1-hash-tables-dictionary): $\Theta(n^2)$. Spread over $m \geq n$ [buckets](#def-b1-hash-tables-hash-table): $\Theta(n)$ expected.

**22.** $2^{10} = 1024$, all with one [hash value](#def-b1-hash-tables-hash-function).

**23.** Which [keys](#def-b1-hash-tables-dictionary) collide depends on the seed, and an attacker who does not know it cannot build colliding [keys](#def-b1-hash-tables-dictionary) in advance; once the seed is known, the attack works again.

**24.** *The anagram attack*: under the additive hash, a set of $k$ distinct letters gives $k!$ [keys](#def-b1-hash-tables-dictionary) in one [bucket](#def-b1-hash-tables-hash-table) (question 19). For $k = 6$, the 720 orders of `dorset` fill a single [bucket](#def-b1-hash-tables-hash-table) of 127 under the additive hash, and spread over all 127 under the polynomial hash, at most 12 per [bucket](#def-b1-hash-tables-hash-table).
