Kodewick
Start learning →
Separate chaining18 / 50

Separate chaining

Lesson 18 of 50 · Part 4 · Hash tables · about 16 minutes

Separate chaining gives each slot of a hash table a linked list: keys that collide hang on the same chain with O(1) head insertion, a search compares along one chain of average length α = n / m, and deleting needs no tombstones.

Open addressing packs every key into one array, slows down as the table fills, and needs tombstones to delete. Another approach is more direct: each slot holds not a key but the head pointer of a linked list, and every key that computes that index hangs on that list. This is separate chaining. Java's HashMap, C++'s unordered_map and Go's map (before 1.24) are built this way. It uses the linked lists of chapter 1: inserting is a head insertion, deleting removes a node.

Buckets and chains

Allocate an array of m pointers, head[m], all NULL at first. To insert k: compute s = k % m, make a new node and put it at the front of head[s] (head insertion, O(1), no walk to the end). To find k: compute s and compare along the chain from head[s], one node at a time.

Again a table of 11 and last lesson's 8 keys, 22 41 53 46 30 13 1 67:

k % 110NULL1NULL2NULL3NULL4NULL5NULL6NULL7NULL8NULL9NULL10NULL

Separate chaining: colliding keys hang on the same chain, and each new one goes at the head

Compared with open addressing, a colliding key only queues with the keys in its own bucket: it never takes anyone else's slot, so there's no clustering.

main.c
1#include <stdio.h>2#include <stdlib.h>3 4#define M 115 6typedef struct Node {7    int key;8    struct Node *next;9} Node;10 11Node *head[M];                   // a global array starts out all NULL12 13void insert(int k) {14    int s = k % M;15    Node *p = malloc(sizeof(Node));16    p->key = k;17    p->next = head[s];           // head insertion: the new node points at the old first one18    head[s] = p;19}20 21int search(int k, int *cmp) {    // returns 1 if found; cmp counts the comparisons22    *cmp = 0;23    for (Node *p = head[k % M]; p; p = p->next) {24        (*cmp)++;25        if (p->key == k) return 1;26    }27    return 0;28}29 30void remove_key(int k) {31    Node **pp = &head[k % M];    // points at "the pointer that points at the current node"32    while (*pp && (*pp)->key != k)33        pp = &(*pp)->next;34    if (*pp) {35        Node *dead = *pp;36        *pp = dead->next;        // the one before now points straight at the one after37        free(dead);38    }39}40 41void show(void) {42    for (int i = 0; i < M; i++) {43        if (!head[i]) continue;44        printf("%2d:", i);45        for (Node *p = head[i]; p; p = p->next)46            printf(" %d", p->key);47        printf("\n");48    }49}50 51int main(void) {52    int keys[] = {22, 41, 53, 46, 30, 13, 1, 67};53    for (int i = 0; i < 8; i++)54        insert(keys[i]);55    show();56    int c;57    int f = search(41, &c);58    printf("find 41: %s, %d comparisons\n", f ? "found" : "not found", c);59    f = search(19, &c);60    printf("find 19: %s, %d comparisons\n", f ? "found" : "not found", c);61    remove_key(30);62    f = search(41, &c);63    printf("after deleting 30, find 41: %d comparisons\n", c);64    return 0;65}
Output
 0: 22
 1: 67 1
 2: 13 46
 8: 30 41
 9: 53
find 41: found, 2 comparisons
find 19: not found, 2 comparisons
after deleting 30, find 41: 1 comparisons

Deleting is an ordinary linked-list delete; every other key is still found afterwards, so there's no need for tombstones. The double pointer pp makes deleting the first node and deleting one in the middle the same code, with no special case for the head.

Guess the outputA wrong guess is fine

Insert 5 12 3 19 26 in order (head insertion). What does bucket 5's chain print, front to back?

1#include <stdio.h>2#include <stdlib.h>3 4#define M 75 6typedef struct Node {7    int key;8    struct Node *next;9} Node;10 11Node *head[M];12 13void insert(int k) {14    Node *p = malloc(sizeof(Node));15    p->key = k;16    p->next = head[k % M];17    head[k % M] = p;18}19 20int main(void) {21    insert(5); insert(12); insert(3); insert(19); insert(26);22    for (Node *p = head[5]; p; p = p->next)23        printf("%d ", p->key);24    printf("\n");25    return 0;26}
Choose one

In this stage's table, the 8 keys 22 41 53 46 30 13 1 67 were inserted at the head in turn. How many comparisons does a search for 46 take?

Put in orderDrag, or use the arrows

Put the four lines of head insertion in order. Table size 7, inserting 1, 8 and 15 in turn (all in bucket 1), so the program prints bucket 1's chain: 15 8 1.

  1. Node *p = malloc(sizeof(Node));
  2. p->key = k;
  3. head[s] = p;
  4. p->next = head[s];
Should print
15 8 1
Exercise 1

Building a table with head insertion

Fill in insert (head insertion) and the printing: table size 7, h(k) = k % 7, one line per non-empty bucket, bucket: key key ….

It should print
1: 1 22 15
2: 16 30 9
4: 4
exercise1.c
1#include <stdio.h>2#include <stdlib.h>3 4#define M 75 6typedef struct Node {7    int key;8    struct Node *next;9} Node;10 11Node *head[M];12 13void insert(int k) {14    // make a node p, p->key = k; p->next = head[k % M]; head[k % M] = p15}16 17int main(void) {18    int keys[] = {15, 22, 9, 30, 1, 16, 4};19    for (int i = 0; i < 7; i++)20        insert(keys[i]);21    for (int i = 0; i < M; i++) {22        if (!head[i]) continue;23        printf("%d:", i);24        // walk head[i] and print each key with a space before it25        printf("\n");26    }27    return 0;28}
Output
Press Run or Ctrl+Enter
Exercise 2

Deleting a key

Fill in remove_key: find k on its chain, make the pointer before it point straight at the node after it, then free it. With the double pointer pp the head needs no special case.

It should print
1: 22 15 8 1
1: 15 1
exercise2.c
1#include <stdio.h>2#include <stdlib.h>3 4#define M 75 6typedef struct Node {7    int key;8    struct Node *next;9} Node;10 11Node *head[M];12 13void insert(int k) {14    Node *p = malloc(sizeof(Node));15    p->key = k;16    p->next = head[k % M];17    head[k % M] = p;18}19 20void remove_key(int k) {21    Node **pp = &head[k % M];22    // while *pp isn't NULL and isn't k: pp = &(*pp)->next; if found: remember it, *pp = its next, free it23}24 25void show(int s) {26    printf("%d:", s);27    for (Node *p = head[s]; p; p = p->next)28        printf(" %d", p->key);29    printf("\n");30}31 32int main(void) {33    int keys[] = {1, 8, 15, 22};34    for (int i = 0; i < 4; i++)35        insert(keys[i]);36    show(1);37    remove_key(22);            // the head38    remove_key(8);             // in the middle39    remove_key(50);            // not in the table40    show(1);41    return 0;42}
Output
Press Run or Ctrl+Enter

The average chain length is α

With n keys scattered over m buckets by a hash function that spreads them evenly, each bucket holds n / m = α keys on average. So:

  • a failed search walks a whole chain: α comparisons on average;
  • a successful search walks a bit over half a chain: about 1 + α / 2 comparisons.

α no longer has to stay below 1: a chain can be any length. But a bigger α means longer chains and slower searches; as long as α is a constant, a search is O(1). So a chaining table also grows: when α passes a threshold (1 here), allocate a new table of about 2m and move every key across, recomputing its index with the new m.

k % m010NULL11621NULL2NULL31383NULL4NULL

A table with m = 5 holding 6 keys, α = 1.2: bucket 3's chain already has 3. Growing to m = 11 (a prime near 2m): take the keys out of the old buckets one by one and recompute each index with k % 11

You can't just move each old chain over whole: the index is k % m, so when m changes, every key's index has to be recomputed. One resize is O(n), but each one doubles the table, so it rarely happens. Running it for real with 1000 random keys, starting at m = 7 and growing whenever α would pass 1:

main.c
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    unsigned key;6    struct Node *next;7} Node;8 9Node **head;10int m = 7, n = 0, moved = 0;11unsigned seed = 1;12 13unsigned next_key(void) {        // a home-made pseudo-random generator: the same every run14    seed = seed * 1664525u + 1013904223u;15    return seed;16}17 18int is_prime(int x) {19    for (int d = 2; d * d <= x; d++)20        if (x % d == 0) return 0;21    return 1;22}23 24void rehash(void) {25    int m2 = 2 * m + 1;26    while (!is_prime(m2)) m2++;                 // a prime near 2m27    Node **h2 = calloc(m2, sizeof(Node *));28    for (int i = 0; i < m; i++) {29        Node *p = head[i];30        while (p) {31            Node *nx = p->next;                 // remember the next one first32            int s = p->key % m2;                // recompute the index with the new size33            p->next = h2[s];34            h2[s] = p;35            p = nx;36            moved++;37        }38    }39    printf("grow: %4d -> %4d (moved %d)\n", m, m2, n);40    free(head);41    head = h2;42    m = m2;43}44 45void insert(unsigned k) {46    if (n + 1 > m) rehash();                    // one more and α would pass 1: grow first47    Node *p = malloc(sizeof(Node));48    p->key = k;49    p->next = head[k % m];50    head[k % m] = p;51    n++;52}53 54int main(void) {55    head = calloc(m, sizeof(Node *));56    for (int i = 0; i < 1000; i++)57        insert(next_key());58    int longest = 0, empty = 0;59    for (int i = 0; i < m; i++) {60        int len = 0;61        for (Node *p = head[i]; p; p = p->next) len++;62        if (len > longest) longest = len;63        if (len == 0) empty++;64    }65    printf("n = %d, m = %d, α = %.2f\n", n, m, (double)n / m);66    printf("longest chain %d, empty buckets %d\n", longest, empty);67    printf("%d moves in all, %.2f per key on average\n", moved, (double)moved / n);68    return 0;69}
Output
grow:    7 ->   17 (moved 7)
grow:   17 ->   37 (moved 17)
grow:   37 ->   79 (moved 37)
grow:   79 ->  163 (moved 79)
grow:  163 ->  331 (moved 163)
grow:  331 ->  673 (moved 331)
grow:  673 -> 1361 (moved 673)
n = 1000, m = 1361, α = 0.73
longest chain 5, empty buckets 664
1307 moves in all, 1.31 per key on average

It grew 7 times and made 1307 moves in all, 1.31 per key on average: in 7 + 17 + 37 + … + 673 each term roughly doubles, so the sum is under twice the last term, and so under 2n. That's the amortized O(1) of chapter 1's doubling realloc. The longest chain has only 5 keys and almost half the buckets are empty, which is what a random spread normally looks like.

Choose one

n = 20 keys spread evenly over m = 8 buckets. How many comparisons does a failed search take on average?

Choose one

When the table grows, why can't the whole chain in the old bucket 3 just be hung on the new table's bucket 3?

Compared with open addressing

Open addressingSeparate chaining
On a collisionFind another slot in the tableHang it on the same chain
Can α exceed 1No, and it's clearly slower above 0.75Yes, the average chain length is α
ClusteringLinear probing has primary clusteringNone, a key only queues within its bucket
DeletingNeeds a tombstoneJust remove the node
Extra spaceNo pointers, but empty slots must be keptOne next pointer per key
CacheGood: all in one contiguous arrayPoor: nodes scattered over the heap, pointers to chase
Who uses itPython dict, Go's map from 1.24Java HashMap, C++ unordered_map

Few keys, speed first and rare deletes: open addressing. An unpredictable number of keys and frequent deletes: chaining. Java's HashMap goes one step further: when a chain reaches 8 keys it is turned into a red-black tree (the balanced trees of chapter 6), so even the worst case is O(log n).

In exams: a chaining question usually gives h(k) and the table length, asks you to draw every chain (watch for head or tail insertion), then compute the ASL for successful and failed searches: success is the sum of each key's position on its chain divided by n, failure is the sum of the chain lengths divided by m (the usual exam convention: comparisons against NULL don't count). The patterns lesson at the end of this chapter works one through.

Choose one

When is chaining the better choice?

Choose allPick all that apply

Which statements about chaining are true? (You can pick more than one.)

Summary

Take-away

Separate chaining: a linked list in every bucket

  • head[m] is a row of list heads; colliding keys hang on the same chain, head insertion O(1)
  • Search: compute the index, compare along the chain; average chain length = α = n / m
  • Deleting removes a list node, no tombstones; α may exceed 1
  • Past a threshold, grow to about 2m and recompute each key's index with the new m, amortized O(1)
1int s = k % M;2Node *p = malloc(sizeof(Node));3p->key = k;4p->next = head[s];5head[s] = p;