TExcelTAD

Hash Tables with Chaining

A hash table stores nn keys from a huge universe UU in a table of mm slots, using a hash function h:U→{0,…,m−1}h : U \to \{0, \ldots, m - 1\} to compute where each key belongs. Key kk hashes to slot h(k)h(k), and h(k)h(k) is its hash value. Collisions, two keys with the same hash value, are unavoidable (Direct-Address Tables), so a hash table needs a policy for them.

The simplest policy is chaining: slot jj holds a linked list, the chain, of all stored keys with hash value jj. This lesson implements chaining and states its costs; the next lesson proves how long the chains are on average. The Hash Tables lesson in the DSA course gives a first look with examples.

The operations

text
CHAINED-INSERT(T, x)            // assumes x.key is not yet in T
1  insert x at the head of the list T[h(x.key)]

CHAINED-SEARCH(T, k)
1  search the list T[h(k)] for an element with key k; return it or NIL

CHAINED-DELETE(T, x)
1  remove x from the list T[h(x.key)]
  • INSERT is O(1)O(1) in the worst case: compute hh, then insert at the head of a list. (If duplicates must be rejected, INSERT has to search first and costs as much as a search.)
  • SEARCH costs O(1)O(1) for the hash plus the length of the chain it scans.
  • DELETE is O(1)O(1) if the chains are doubly linked and xx is the element itself: no search is needed, as in Doubly Linked Lists with Sentinels. Deleting by key costs a search.

So everything hinges on the chain lengths. In the worst case all nn keys hash to one slot and the table is a linked list with Θ(n)\Theta(n) searches. The point of a good hash function is to make that extremely unlikely.

Watching collisions

The animation uses a deliberately weak hash function: the sum of the character codes, modulo m=7m = 7. Anagrams such as cat and act have the same sum, so they always collide.

The Python table does the same operations with the same hash and prints each step. Like the animation it adds new keys at the end of a chain (a Python list), so the chains read in insertion order; adding at the head, as in the pseudocode, gives the same costs.

python · try it yourself
class ChainedTable:
    def __init__(self, m, h):
        self.m, self.h = m, h
        self.slots = [[] for _ in range(m)]
    def put(self, key):
        j = self.h(key, self.m)
        chain = self.slots[j]
        if key in chain:
            return f"put {key!r}: already in slot {j}"
        chain.append(key)
        return f"put {key!r}: slot {j}" + (f", collision: chain {chain}" if len(chain) > 1 else "")
    def get(self, key):
        j = self.h(key, self.m)
        for steps, k in enumerate(self.slots[j], 1):
            if k == key:
                return f"get {key!r}: found in slot {j} after {steps} key comparison(s)"
        return f"get {key!r}: not in slot {j} ({len(self.slots[j])} comparison(s))"
    def remove(self, key):
        j = self.h(key, self.m)
        self.slots[j].remove(key)
        return f"remove {key!r}: slot {j}"

def char_sum(key, m):
    return sum(map(ord, key)) % m

t = ChainedTable(7, char_sum)
for op in ["put cat", "put dog", "put act", "put emu", "put owl", "put yak", "get act", "remove dog", "get dog"]:
    name, key = op.split()
    print(getattr(t, name)(key))
print("slots:", t.slots)
put 'cat': slot 4
put 'dog': slot 6
put 'act': slot 4, collision: chain ['cat', 'act']
put 'emu': slot 5
put 'owl': slot 2
put 'yak': slot 3
get 'act': found in slot 4 after 2 key comparison(s)
remove 'dog': slot 6
get 'dog': not in slot 6 (0 comparison(s))
slots: [[], [], ['owl'], ['yak'], ['cat', 'act'], ['emu'], []]

A search for a missing key only scans one chain, here an empty one: the table answers "no" without looking at any other key.

Load factor

The load factor of a table with nn keys in mm slots is

α=nm\alpha = \frac{n}{m}

the average chain length. With chaining α\alpha can exceed 1; keys never "overflow". The next lesson shows that, under the assumption that hh spreads keys like a random function, an unsuccessful search costs Θ(1+α)\Theta(1 + \alpha) expected time and a successful one 1+α/2−α/(2n)1 + \alpha/2 - \alpha/(2n) comparisons on average. So if mm grows in proportion to nn, keeping α\alpha bounded by a constant, every operation takes expected O(1)O(1) time. Tables do that by rehashing: when α\alpha passes a threshold, allocate about twice as many slots and reinsert every key, which by the doubling argument costs O(1)O(1) amortized per insert.

The program fills a table with 2000 random integer keys, growing it whenever α\alpha would exceed 1, and reports the chain lengths at the end.

python · try it yourself
import random
from collections import Counter

class GrowingTable:
    def __init__(self):
        self.m, self.n, self.slots, self.rehashed = 8, 0, [[] for _ in range(8)], 0
    def insert(self, k):
        if self.n + 1 > self.m:                       # keep alpha <= 1
            old = [x for chain in self.slots for x in chain]
            self.m *= 2
            self.slots = [[] for _ in range(self.m)]
            for x in old:
                self.slots[x % self.m].append(x)
            self.rehashed += len(old)
        self.slots[k % self.m].append(k)
        self.n += 1

rng = random.Random(3)
t = GrowingTable()
for k in rng.sample(range(10 ** 9), 2000):
    t.insert(k)
lengths = Counter(len(c) for c in t.slots)
print(f"n = {t.n}, m = {t.m}, alpha = {t.n / t.m:.3f}, keys moved by rehashing: {t.rehashed}")
print("chain length -> number of slots:", dict(sorted(lengths.items())))
print("longest chain:", max(lengths))
n = 2000, m = 2048, alpha = 0.977, keys moved by rehashing: 2040
chain length -> number of slots: {0: 761, 1: 767, 2: 368, 3: 116, 4: 31, 5: 5}
longest chain: 5

The counts are close to a Poisson distribution with mean α\alpha: about e−1≈37%e^{-1} \approx 37\% empty slots, as many with one key, and a fast-shrinking tail. The longest chain is 5 for 2048 slots; for random hashing it grows like Θ(lg⁡m/lg⁡lg⁡m)\Theta(\lg m / \lg \lg m), the balls-into-bins maximum load. Rehashing moved 2040 keys in total, about one per insert.

In C++

The C++ table keeps a std::vector of std::list chains and rehashes when α\alpha would exceed 1. The program inserts the same kind of keys, deletes every third one through the stored iterator (no search), and compares the bucket statistics with the standard library's std::unordered_set, which also uses chaining and keeps max_load_factor() = 1 by default.

cpp · try it yourself
#include <cstdio>
#include <list>
#include <random>
#include <unordered_set>
#include <vector>

class ChainedSet {
    std::vector<std::list<unsigned>> slots_ = std::vector<std::list<unsigned>>(8);
    std::size_t n_ = 0;
    std::size_t slot(unsigned k) const { return k % slots_.size(); }
public:
    std::size_t size() const { return n_; }
    std::size_t buckets() const { return slots_.size(); }
    bool contains(unsigned k) const {
        for (unsigned x : slots_[slot(k)]) if (x == k) return true;
        return false;
    }
    std::list<unsigned>::iterator insert(unsigned k) {          // k must not be present
        if (n_ + 1 > slots_.size()) {
            std::vector<std::list<unsigned>> bigger(2 * slots_.size());
            for (auto& chain : slots_)
                while (!chain.empty()) {                 // splice moves the node itself, so
                    auto& to = bigger[chain.front() % bigger.size()];   // iterators stay valid
                    to.splice(to.begin(), chain, chain.begin());
                }
            slots_.swap(bigger);
        }
        ++n_;
        auto& chain = slots_[slot(k)];
        chain.push_front(k);
        return chain.begin();
    }
    void erase(unsigned k, std::list<unsigned>::iterator it) { slots_[slot(k)].erase(it); --n_; }
    std::size_t longest() const {
        std::size_t best = 0;
        for (auto& c : slots_) best = std::max(best, c.size());
        return best;
    }
};

int main() {
    std::mt19937 rng(3);
    ChainedSet t;
    std::unordered_set<unsigned> ref;
    std::vector<std::pair<unsigned, std::list<unsigned>::iterator>> handles;
    while (ref.size() < 2000) {
        unsigned k = rng() % 1000000000u;
        if (ref.insert(k).second) handles.push_back({k, t.insert(k)});
    }
    std::printf("mine: n = %zu, m = %zu, longest chain %zu\n", t.size(), t.buckets(), t.longest());
    std::printf("std::unordered_set: n = %zu, buckets = %zu, load factor %.3f\n",
                ref.size(), ref.bucket_count(), ref.load_factor());
    for (std::size_t i = 0; i < handles.size(); i += 3) {
        t.erase(handles[i].first, handles[i].second);
        ref.erase(handles[i].first);
    }
    bool agree = true;
    for (auto& [k, it] : handles) agree = agree && (t.contains(k) == (ref.count(k) == 1));
    std::printf("after deleting every third key: n = %zu, agree with std::unordered_set: %s\n",
                t.size(), agree ? "yes" : "no");
}
mine: n = 2000, m = 2048, longest chain 5
std::unordered_set: n = 2000, buckets = 2357, load factor 0.849
after deleting every third key: n = 1333, agree with std::unordered_set: yes

The deletions use the iterators returned by insert: each one unlinks a node from a doubly linked std::list in O(1)O(1), without scanning the chain. For that to work after a rehash, the rehash must move the list nodes with splice rather than copy the keys into new nodes; copying would leave every stored iterator dangling (an early version of this program crashed exactly that way). GCC's std::unordered_set grows its bucket array to prime sizes, which is why its bucket count is not a power of two.

Test yourself

A chained hash table has m=100m = 100 slots and n=250n = 250 keys. What is the load factor?

  1. 0.4
  2. 2.5
  3. 250
  4. it cannot hold more than 100 keys

What is the worst-case cost of CHAINED-SEARCH with nn keys?

  1. O(1)O(1)
  2. O(α)O(\alpha)
  3. Θ(n)\Theta(n), if all keys hash to the same slot
  4. O(lg⁡n)O(\lg n)

Why are the chains often doubly linked?

  1. To search faster
  2. So DELETE given the element itself takes O(1)O(1)
  3. To store two keys per node
  4. To allow α>1\alpha > 1

In the character-sum hash, why do cat and act always collide?

  1. They have the same length
  2. Their character codes have the same sum, whatever mm is
  3. Because m=7m = 7 is prime
  4. They do not collide for m=13m = 13