কম্পিউটার বিজ্ঞান · বই 3 · স্নাতক প্রথম বর্ষ

University Computer Science — Year 1

এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: 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 2202^{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 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 2642^{64} 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 Θ(n)\Theta(n); a sorted array searches in Θ(log⁡n)\Theta(\log n) but inserts in Θ(n)\Theta(n). 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 mm positions, the position of a key is its hash value modulo mm.

For integer keys, the division method takes k mod mk \bmod m, with mm 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 s031L−1+s131L−2+⋯+sL−1 mod 264s_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, 240+28+1792^{40} + 2^8 + 179, 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;
}
Listing 16.1. The additive, polynomial and FNV-1a hash functions 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 of six keys, 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⋅31+97=66⋅31+66=211265 \cdot 31 + 97 = 66 \cdot 31 + 66 = 2112. With m=31m = 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 110 mod 31=17110 \bmod 31 = 17, the bucket of its n); only the wrap modulo 2642^{64} 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 mm buckets; the key kk belongs to bucket h(k) mod mh(k) \bmod m. 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 nn keys in mm buckets is α=n/m\alpha = n/m. Rehashing moves every entry to a new 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.)
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.)
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 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 n>mn > m, which keeps α≤1\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.

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 Θ(n)\Theta(n). 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 mm buckets, independently of the other keys.

Under this assumption, a chain holds α\alpha keys on average, an unsuccessful search compares α\alpha keys and a successful one about 1+α/21 + \alpha/2, so that with mm proportional to nn 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.
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.

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;
}
Listing 16.3. Searching with linear probing, past tombstones 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 hashed by their first letter into 11 slots: a cluster forms; a deletion leaves a tombstone 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 12(1+11−α)\frac12(1 + \frac{1}{1 - \alpha}) for a successful search and 12(1+1(1−α)2)\frac12(1 + \frac{1}{(1 - \alpha)^2}) for an unsuccessful one, so the table must stay well below full; this one doubles when keys and tombstones 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.
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.

The counts of the two designs, as the 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).
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\alpha = 0.7, then explodes for absent keys (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=216m = 2^{16}.

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 nn insertions is O(n)O(n), 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
Output 16.5. Keys moved by the rehashes of nn insertions, doubling at load 34\frac34. Some lines are left out.

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 2k2^k strings of length 2k2k 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
Output 16.6. 1024 strings built from 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 m=11m = 11, 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 h(k)=k mod 13h(k) = k \bmod 13 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 m=10m = 10. Give the chain lengths with chaining.

Solution

Solution of Exercise 16.3.

The buckets are 0, 0, 0, 1 and 1: chains of length 3 and 2, and eight empty buckets.

Exercise 16.4 ★

A chaining table of 16 buckets doubles when n>mn > m. What are mm and α\alpha after 17, 33 and 100 insertions?

Solution

Solution of Exercise 16.4.

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

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;
}
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

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 mm, 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 m≥26m \geq 26: the longest chain is the number of people sharing the commonest initial, 9, whatever mm, and only the 26 buckets of the initials used can be occupied, so 127−26=101127 - 26 = 101 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;
}
A set of integers by linear probing code/bachelor-1/16-hash-tables/exercises/intset.c

The home slot multiplies the key by a large odd constant before taking it modulo mm, 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 nn keys fall into one bucket, there are n(n−1)/2n(n - 1)/2 colliding pairs, and that if they are spread as evenly as possible over mm buckets, there are about n2/(2m)n^2/(2m).

Solution

Solution of Exercise 16.9.

A bucket of ℓ\ell keys holds (ℓ2)\binom{\ell}{2} colliding pairs. One bucket of nn: n(n−1)/2n(n - 1)/2. Evenly, mm buckets of n/mn/m: m⋅(n/m)(n/m−1)2=n(n−m)2m≈n22mm \cdot \frac{(n/m)(n/m - 1)}{2} = \frac{n(n - m)}{2m} \approx \frac{n^2}{2m} when m≪nm \ll n, and about mm times fewer pairs.

Exercise 16.10 ★★★

A table starts with 8 slots and, after an insertion that makes n>34mn > \frac34 m, doubles and rehashes its nn keys. Prove that nn insertions move fewer than 2n+log⁡2n2n + \log_2 n 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 m0=8m_0 = 8, m1=16m_1 = 16, …, mj=8⋅2jm_j = 8 \cdot 2^j slots, each when the table holds 34mi+1\frac34 m_i + 1 keys, which it moves. In all: ∑i=0j(34mi+1)=34(2mj−8)+j+1=32mj+j−5\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 nn-th insertion, so 34mj+1≤n\frac34 m_j + 1 \leq n, that is 32mj≤2n−2\frac32 m_j \leq 2n - 2, and j=log⁡2(mj/8)<log⁡2nj = \log_2 (m_j/8) < \log_2 n: the moves total at most 2n+j−7<2n+log⁡2n2n + j - 7 < 2n + \log_2 n. Right after a doubling, n=34mj+1n = \frac34 m_j + 1 and the total is 2n+j−72n + j - 7, so the ratio is close to 2; it falls to about 1 just before the next doubling, when n≈32mjn \approx \frac32 m_j insertions have shared the same 32mj\frac32 m_j moves. The output shows 1.966 at n=100 000n = 100\,000, just past the doubling at 98 305 keys, and 1.229 at n=10 000n = 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 kk distinct strings of length LL with the same value of h(s)=∑isi31L−1−i mod 264h(s) = \sum_i s_i 31^{L-1-i} \bmod 2^{64}, 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)]
Strings made of equal-hash blocks code/bachelor-1/16-hash-tables/exercises/collide.py

Split ss into L/2L/2 blocks of two characters: h(s)=∑jvj 31L−2−2j mod 264h(s) = \sum_j v_j\, 31^{L - 2 - 2j} \bmod 2^{64} with vj=31s2j+s2j+1v_j = 31 s_{2j} + s_{2j+1} the value of block jj. Both Aa and BB have value 2112, so every string made of such blocks has the same sum, as an integer and so modulo 2642^{64}; there are 2L/22^{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. Among the 26426^4 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 264=456 97626^4 = 456\,976 words of four letters, the sums run from 4⋅97=3884 \cdot 97 = 388 to 4⋅122=4884 \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⋅109.5=4384 \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 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
Output 16.8. The town’s names under four hash functions.
$ 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.

Part I — Four hash functions.

  1. With 120 keys and m=31m = 31, what is the smallest possible longest chain? Which functions come close?
  2. Explain the polynomial hash’s longest chain of 18 at m=31m = 31, and why it drops at m=64m = 64 and 127.
  3. Why does the first-character hash give the same longest chain for every m≥26m \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? (Think of short keys, and of Exercise 16.12.)
  5. Which of the four would you choose, and why?
  6. Why must equal keys have equal hash values, but unequal keys need not have unequal ones?

Part II — Chaining.

  1. For FNV-1a, compare the keys compared per successful search with 1+α/21 + \alpha/2 for the three values of mm.
  2. With 120 keys in 127 buckets, about how many buckets should stay empty under uniform hashing? Compare with the table.
  3. Prove that the average number of keys compared per successful search is 1n∑bℓb(ℓb+1)2\frac1n \sum_b \frac{\ell_b(\ell_b + 1)}{2}, where ℓb\ell_b is the length of chain bb (keys added at the end of their chain).
  4. Deduce that, for fixed nn and mm, this average is smallest when the chains are as equal as possible.
  5. What does a search for an absent key cost, in the worst case and on average?
  6. Why does the table of the problem not resize?

Part III — Open addressing.

  1. Compute α\alpha for 127 and 251 slots, and compare the FNV-1a probes with 12(1+11−α)\frac12(1 + \frac{1}{1 - \alpha}).
  2. Why does the first-character hash cost about 50 probes per search, whatever the table size?
  3. Explain why a cluster grows faster the longer it is.
  4. Why does probing need m>nm > n, while chaining works with m<nm < n?
  5. Why can a search stop at a free slot but not at a tombstone?
  6. When the table is resized, what happens to the tombstones?

Part IV — An attacker’s names.

  1. Prove that, under the additive hash, a set of kk distinct letters gives k!k! keys in one bucket.
  2. Read Output 16.9: how many buckets do the 720 keys use under each hash?
  3. With nn keys in one bucket, what does inserting all of them cost with chaining? And with a hash that spreads them over m≥nm \geq n buckets?
  4. An attacker knows the polynomial hash. How many names of length 20 with one hash value can he build from Aa and BB (Output 16.6)?
  5. Why does a random seed defeat that attack, and why must the seed stay secret?
  6. State the named result of the problem, the anagram attack, with its proof and the numbers printed.
Solution

Solution of Problem 16.1.

1. ⌈120/31⌉=4\lceil 120/31 \rceil = 4. 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 si31L−1−is_i 31^{L-1-i} but the last is 0: for a name short enough not to wrap modulo 2642^{64}, the bucket is its last character modulo 31. Eighteen names end in y, and 121 mod 31=28121 \bmod 31 = 28: fifteen of them, the short ones, fill bucket 28, and three longer names, whose hash wrapped, land there by chance: 18. For m=64m = 64 or 127 the multiplier 31 is invertible modulo mm and every character counts.

3. At most 26 initials, distinct modulo m≥26m \geq 26 (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 26426^4 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 mm; the polynomial hash is as good when mm 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. α=3.87,1.875,0.945\alpha = 3.87, 1.875, 0.945 give 1+α/2=2.94,1.94,1.471 + \alpha/2 = 2.94, 1.94, 1.47; the table shows 2.92, 1.89, 1.47.

8. 127(1−1127)120≈127e−0.945≈49127(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 jj of its chain costs jj comparisons; a chain of ℓb\ell_b keys costs 1+⋯+ℓb1 + \dots + \ell_b in all; divide by nn.

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

11. The whole chain: nn in the worst case, α\alpha on average under uniform hashing.

12. To compare the hash functions at fixed mm; a resizing table would change mm during the experiment.

13. α=0.945\alpha = 0.945 and 0.4780.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; 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 cc grows with probability about (c+1)/m(c + 1)/m, 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 kk distinct letters have k!k! distinct orders: k!k! 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 ii-th insertion first searches the i−1i - 1 keys: Θ(n2)\Theta(n^2). Spread over m≥nm \geq n buckets: Θ(n)\Theta(n) expected.

22. 210=10242^{10} = 1024, 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 kk distinct letters gives k!k! keys in one bucket (question 19). For k=6k = 6, 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.

এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ

পরিভাষায় সব 1050 টি শব্দ দেখো