algoritmauzmanı
Sign in
TREN
9.4Hashing Applications
Lesson 9.4.1

Resizing (rehashing)

The speed of a hash table depends on its . As keys are added, α grows: chains get longer and probes multiply. The fix is to grow the table. But this is not as simple as growing an array: when the number of buckets changes, k % m changes too, and every key's place has to be computed again. This is called .

What you will learn
  • When the table is grown and to what size
  • Why keys cannot be copied to their old places and how they are placed again
  • Why insertion stays O(1) on average even though growing is expensive
7 minTime O(n + M)Memory O(M)C · Java · Python

1Idea

In this lesson the number of buckets is not a fixed M but the table's own field m, and the buckets are an array allocated with that size. The insert function looks at the load factor after every insertion. With chaining the threshold is usually 1, so the table grows once count > m. With open addressing the threshold is lower, often 0.5, because the number of probes rises fast as α gets close to 1.

// the end of insert (9.3.1), m is now a field of the tablet->count++;if (t->count > t->m)            // load factor went above 1    rehash(t);return true;

The new size is the first prime larger than twice the old one: from 5 to 11, from 11 to 23. Doubling means the table grows rarely; a prime keeps the keys spread evenly over the buckets with the division method.

The keys cannot be copied into the new array under their old bucket numbers. 12 is in bucket 2 when m = 5 but belongs in bucket 1 when m = 11; if it stays in its old place a search never finds it. So every chain of the old table is walked and each node's new bucket is computed from scratch with data % newM. The nodes are not allocated again, only their links change: each one is moved to the head of its new bucket's chain. At the end only the old array of pointers is released.

Rehashing with open addressing is the same idea: the keys in the filled cells of the old array are inserted from scratch into the new array. Cells marked as deleted are not moved, so growing also clears out the markers that have piled up.

2Step by step

In the drawing, inserting 18 into a table with m = 5 brought the number of keys to 6 and pushed the load factor above 1. The table grows to m = 11; the nodes are moved in the order of the old buckets. At each step the matching lines of code light up.

old table (m = 5)new table (m = 11)NULLNULLNULLNULL0count 6 > m 5123401234567891010?12?7?18?3?9?
  1. Start. 5 buckets hold 6 keys: α = 6 / 5 = 1.2 is over the threshold. The chains of buckets 2 and 3 have two nodes each.
  2. The new size is computed: 2 × 5 + 1 = 11 is prime. An empty array of 11 buckets is allocated.
  3. 10 from bucket 0 is moved. 10 % 11 = 10, so it goes to bucket 10 of the new table.
  4. The first node of bucket 2 is 12: 12 % 11 = 1. It used to share a bucket with 7; now they are apart.
  5. 7: 7 % 11 = 7. The old bucket 2 is now empty.
  6. 18 from bucket 3: 18 % 11 = 7. Bucket 7 is already in use; 18 goes to the head of the chain.
  7. 3: 3 % 11 = 3.
  8. 9 from bucket 4: 9 % 11 = 9. Every node has been moved.
  9. The old array of pointers is released and the table uses the new array with m = 11. α = 6 / 11 ≈ 0.55. No node was allocated again.

struct Node {    int data;    struct Node* next;}; struct HashTable {    struct Node** buckets;          // array of m pointers    int m;                          // number of buckets    int count;}; bool isPrime(int n) {    if (n < 2) return false;    for (int d = 2; d * d <= n; d++)        if (n % d == 0) return false;    return true;} bool rehash(struct HashTable* t) {    int newM = 2 * t->m + 1;    while (!isPrime(newM)) newM++;          // first prime above twice the size    struct Node** fresh = calloc(newM, sizeof(struct Node*));    if (fresh == NULL) return false;    for (int i = 0; i < t->m; i++) {        struct Node* temp = t->buckets[i];        while (temp != NULL) {            struct Node* following = temp->next;            int j = temp->data % newM;      // hash for the new size            temp->next = fresh[j];          // move to the head of the new chain            fresh[j] = temp;            temp = following;        }    }    free(t->buckets);                       // the old array, not the nodes    t->buckets = fresh;    t->m = newM;    return true;}
class Node {    int data;    Node next;    Node(int data) { this.data = data; }} class ChainedHashTable {    Node[] buckets;    int m;                          // number of buckets    int count = 0;     ChainedHashTable(int m) { this.m = m; buckets = new Node[m]; }     boolean isPrime(int n) {        if (n < 2) return false;        for (int d = 2; d * d <= n; d++)            if (n % d == 0) return false;        return true;    }     void rehash() {        int newM = 2 * m + 1;        while (!isPrime(newM)) newM++;      // first prime above twice the size        Node[] fresh = new Node[newM];        for (int i = 0; i < m; i++) {            Node temp = buckets[i];            while (temp != null) {                Node following = temp.next;                int j = temp.data % newM;       // hash for the new size                temp.next = fresh[j];           // move to the head of the new chain                fresh[j] = temp;                temp = following;            }        }        buckets = fresh;        m = newM;    }}
class Node:    def __init__(self, data):        self.data = data        self.next = None class ChainedHashTable:    def __init__(self, m):        self.m = m                  # number of buckets        self.buckets = [None] * m        self.count = 0     def is_prime(self, n):        if n < 2:            return False        d = 2        while d * d <= n:            if n % d == 0:                return False            d += 1        return True     def rehash(self):        new_m = 2 * self.m + 1        while not self.is_prime(new_m):     # first prime above twice the size            new_m += 1        fresh = [None] * new_m        for i in range(self.m):            temp = self.buckets[i]            while temp is not None:                following = temp.next                j = temp.data % new_m       # hash for the new size                temp.next = fresh[j]        # move to the head of the new chain                fresh[j] = temp                temp = following        self.buckets = fresh        self.m = new_m

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(n + M)

Every node is moved once and every bucket of the old array is looked at: O(n + M). But this work is done rarely.

Memory
O(M)

O(M) for the new array of buckets; the nodes stay where they are.

The size doubles each time, so more and more insertions happen between two resizes. The total cost of resizing over n insertions is O(n), that is O(1) per insertion. It is the same calculation as growing a dynamic array.

4Common mistake

A common mistake is copying the old array into the new one bucket by bucket:

for (int i = 0; i < t->m; i++)    fresh[i] = t->buckets[i];   // old bucket number

This code is fast but wrong. 12 was in bucket 2 when m = 5 and is still there; but in the new table search(12) looks in bucket 12 % 11 = 1 and does not find it. When the number of buckets changes, every key's hash changes; each one must be placed again for the new size.

5Try it

If a chained table with m = 11 is grown, how many buckets does it get?

Show the answer

The answer is B. 2 × 11 + 1 = 23 is prime, so the first prime above twice the size is 23.

After the table grows, which bucket holds the key 25? (old m = 5, new m = 11)

Show the answer

The answer is B. With rehashing every key's bucket is computed again for the new size: 25 % 11 = 3.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.