এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।
University Computer Science — Year 1 · স্নাতক প্রথম বর্ষ
16Hash Tables
A directory of a million names, sorted alphabetically, finds any name in about twenty looks: binary search halves the candidates each time, and 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 does this: a function computes a position from the key, and the table deals with the keys that land on the same position. Its expected cost per operation is constant, under an assumption about the keys that an adversary can break, which this chapter also shows, with the defence.
You already know
A dynamic array that doubles when full has amortised constant cost per insertion (Chapter 14). A singly linked list inserts and removes at a known link in constant time (Chapter 15). Unsigned integer arithmetic in C is exact modulo for uint64_t (Chapter 2).
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 ; a sorted array searches in but inserts in . Python’s dict and set, used since the first programming chapters, are hash tables; 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 must have equal hash values. For a table of positions, the position of a key is its hash value modulo .
For integer keys, the division method takes , with 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 , evaluated by Horner’s scheme; and FNV-1a, which mixes in each byte with an exclusive or and multiplies by a fixed prime, , starting from a fixed offset basis.
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;
}
$ 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
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: . With , 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 , the bucket of its n); only the wrap modulo of longer keys disturbs this. The multiplier and the table size must not share a factor. A good hash function spreads the keys 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 in an array of buckets; the key belongs to bucket . Two different keys in the same bucket form a collision.
Definition 16.4 (Separate chaining, open addressing, linear probing, tombstone)
In separate chaining, each bucket holds a linked list of the entries that belong to it. In open addressing, all entries live in the 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 keys in buckets is . Rehashing moves every entry to a new array of a different size, recomputing its position.
dog and saw land in the same bucket, which then holds a list of two entries. Empty buckets hold null pointers. (Illustrative positions.)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;
}
The function find returns a pointer to the link that leads to the key’s cell, as the removal of Chapter 15 did; insertion, search and deletion all use it. With resizing on, the table doubles its buckets when , which keeps .
$ 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
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, and a search costs . The average case needs an assumption on the keys.
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 buckets, independently of the other keys.
Under this assumption, a chain holds keys on average, an unsuccessful search compares keys and a successful one about , so that with proportional to every operation has constant expected cost. The proof needs expectations of random variables, and belongs to the second year; the counts below check it.
16.4 Open addressing
Open addressing avoids the lists and their pointers: the 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.
// 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;
}
$ 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
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 keeps the chain of probes intact, and a later insertion can reuse it. The demonstration also shows the weakness of linear probing: 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 for a successful search and for an unsuccessful one, so the table must stay well below full; this one doubles when keys and tombstones fill three quarters of it.
The counts of the two designs, as the load factor grows, come from a simulation with random positions:
$ 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
Here chaining wins at every load factor. Probing touches consecutive slots of one array, which suits the memory hierarchy, but each slot of this table holds a pointer to its key, so every probe also follows a pointer to compare the key, and the advantage of the contiguous array is lost; near a full table the long clusters add the rest. Tables that store short keys, 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 passes a threshold rehashes every key, at a cost proportional to the number of keys; as for the dynamic array, the total over insertions is , an amortised constant per insertion (Exercise 16.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
The expected constant cost rests on the assumption that the keys spread evenly. Keys chosen by an adversary need not. Under the additive hash, every reordering of a word lands in the same bucket; under the polynomial hash, the blocks Aa and BB can be combined into strings of length with one hash value. A server that stores the names of the fields of a request in a 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
Aa and BB: one polynomial hash value; FNV-1a with three seeds spreads them, differently each time.The defence is a 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 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 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 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 , give the bucket of the keys 15, 26, 37, 100 and 121. Which collide?
Solution
Solution of Exercise 16.1.
Buckets 4, 4, 4, 1 and 0: 15, 26 and 37 collide (they differ by multiples of 11).
Exercise 16.2 ★
Insert the keys 18, 41, 22, 44, 59, 32, 31, 73 in this order into a table of 13 slots with and linear probing. Draw the table.
Solution
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 have additive hash values 300, 310, 320, 331 and 341, and . Give the chain lengths with chaining.
Exercise 16.4 ★
A chaining table of 16 buckets doubles when . What are and after 17, 33 and 100 insertions?
Solution
Solution of Exercise 16.4.
After 17 insertions, and ; after 33, , ; after 100 (the 65th doubled again), , .
Exercise 16.5 ★★
This deletion marks the slot free. Explain the output, and repair the deletion.
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;
}
find(24) = -1, find(5) = 6, find(10) = 3
Solution
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 (a third value, say -2) that find skips and put may reuse, as Listing 16.3 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): why does the longest chain stay 9 whatever , and why do 101 of 127 buckets stay empty? What does linear probing cost with it?
Solution
Solution of Exercise 16.6.
The first characters are capital letters, at most 26 values, which stay distinct modulo any : the longest chain is the number of people sharing the commonest initial, 9, whatever , and only the 26 buckets of the initials used can be occupied, so stay empty. With linear probing 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 with linear probing (no deletion), doubling when three quarters full, and test it against an array of booleans.
Solution
Solution of Exercise 16.7.
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;
}
The home slot multiplies the key by a large odd constant before taking it modulo , which spreads consecutive integers. Before an insertion that would pass three quarters, every key is placed again in an array twice as large. The test adds 50 000 random values below 100 000 and checks every value against an 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
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 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 keys fall into one bucket, there are colliding pairs, and that if they are spread as evenly as possible over buckets, there are about .
Exercise 16.10 ★★★
A table starts with 8 slots and, after an insertion that makes , doubles and rehashes its keys. Prove that insertions move fewer than keys in all, that the number of moves per insertion comes close to 2 just after a doubling, and compare with Output 16.5.
Solution
Solution of Exercise 16.10.
The doublings happen from , , …, slots, each when the table holds keys, which it moves. In all: . The last doubling happened at or before the -th insertion, so , that is , and : the moves total at most . Right after a doubling, and the total is , so the ratio is close to 2; it falls to about 1 just before the next doubling, when insertions have shared the same moves. The output shows 1.966 at , just past the doubling at 98 305 keys, and 1.229 at , long after the one at 6145. Amortised, a rehash costs a constant per insertion.
Exercise 16.11 ★★★
Write colliding(k, L), which returns distinct strings of length with the same value of , and test it. Prove that it works.
Solution
Solution of Exercise 16.11.
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)]
Split into blocks of two characters: with the value of block . Both Aa and BB have value 2112, so every string made of such blocks has the same sum, as an integer and so modulo ; there are 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. Among the words of four letters a to z, how many share the most common additive hash value? Count it with a program, and explain why it is the middle value.
Solution
Solution of Exercise 16.12.
Addition is commutative: the sum of the characters does not depend on their order. Over the words of four letters, the sums run from to , 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 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 with chaining, and of 127 and 251 slots with linear probing, under the four hash functions, and reports the longest chain, the empty buckets, 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
$ 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
Part I — Four hash functions.
- With 120 keys and , what is the smallest possible longest chain? Which functions come close?
- Explain the polynomial hash’s longest chain of 18 at , and why it drops at and 127.
- Why does the first-character hash give the same longest chain for every ?
- On these names the additive hash does about as well as FNV-1a. Why is it nevertheless a poor general hash function? (Think of short keys, and of Exercise 16.12.)
- Which of the four would you choose, and why?
- Why must equal keys have equal hash values, but unequal keys need not have unequal ones?
Part II — Chaining.
- For FNV-1a, compare the keys compared per successful search with for the three values of .
- With 120 keys in 127 buckets, about how many buckets should stay empty under uniform hashing? Compare with the table.
- Prove that the average number of keys compared per successful search is , where is the length of chain (keys added at the end of their chain).
- Deduce that, for fixed and , this average is smallest when the chains are as equal as possible.
- What does a search for an absent key cost, in the worst case and on average?
- Why does the table of the problem not resize?
Part III — Open addressing.
- Compute for 127 and 251 slots, and compare the FNV-1a probes with .
- Why does the first-character hash cost about 50 probes per search, whatever the table size?
- Explain why a cluster grows faster the longer it is.
- Why does probing need , while chaining works with ?
- Why can a search stop at a free slot but not at a tombstone?
- When the table is resized, what happens to the tombstones?
Part IV — An attacker’s names.
- Prove that, under the additive hash, a set of distinct letters gives keys in one bucket.
- Read Output 16.9: how many buckets do the 720 keys use under each hash?
- With keys in one bucket, what does inserting all of them cost with chaining? And with a hash that spreads them over buckets?
- An attacker knows the polynomial hash. How many names of length 20 with one hash value can he build from
AaandBB(Output 16.6)? - Why does a random seed defeat that attack, and why must the seed stay secret?
- State the named result of the problem, the anagram attack, with its proof and the numbers printed.
Solution
Solution of Problem 16.1.
1. . None reaches it: the first letter gives 9 (with 5 empty buckets), 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 but the last is 0: for a name short enough not to wrap modulo , the bucket is its last character modulo 31. Eighteen names end in y, and : fifteen of them, the short ones, fill bucket 28, and three longer names, whose hash wrapped, land there by chance: 18. For or 127 the multiplier 31 is invertible modulo and every character counts.
3. At most 26 initials, distinct modulo (Exercise 16.6).
4. It ignores the order of the characters, so anagrams always collide (question 19), and short keys have sums in a narrow range: the words of four letters take only 101 values, so a table of a thousand buckets would use at most 101 of them.
5. FNV-1a: it uses every byte, mixes them, and has no relation with any ; the polynomial hash is as good when is coprime with 31.
6. A search looks only in the key’s bucket, so equal keys must meet there. Unequal keys cannot all have different values: there are infinitely many strings and finitely many hash values.
7. give ; the table shows 2.92, 1.89, 1.47.
8. . The table shows 51 for FNV-1a, 53 and 43 for the others.
9. The key in position of its chain costs comparisons; a chain of keys costs in all; divide by .
10. If two chains have lengths , moving a key from the first to the second changes the sum by : the minimum has all lengths within one of each other.
11. The whole chain: in the worst case, on average under uniform hashing.
12. To compare the hash functions at fixed ; a resizing table would change during the experiment.
13. and ; 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; 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 grows with probability about , and long clusters also merge.
16. Every key occupies its own slot of the array.
17. A free slot was free when every key now present was inserted, so no probe sequence ever passed it; a tombstone was occupied, and a later key may have gone past it.
18. They disappear: only the live entries are inserted into the new array.
19. The additive hash is invariant under permutation, and distinct letters have distinct orders: different keys, one hash value, one bucket.
20. 1 bucket for the additive hash; all 127 for the polynomial, the largest holding 12 keys.
21. In one chain, the -th insertion first searches the keys: . Spread over buckets: expected.
22. , all with one hash value.
23. Which keys collide depends on the seed, and an attacker who does not know it cannot build colliding keys in advance; once the seed is known, the attack works again.
24. The anagram attack: under the additive hash, a set of distinct letters gives keys in one bucket (question 19). For , the 720 orders of dorset fill a single bucket of 127 under the additive hash, and spread over all 127 under the polynomial hash, at most 12 per bucket.