Hash Tables with Chaining
A hash table stores keys from a huge universe in a table of slots, using a hash function to compute where each key belongs. Key hashes to slot , and 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 holds a linked list, the chain, of all stored keys with hash value . 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
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 in the worst case: compute , 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 for the hash plus the length of the chain it scans.
- DELETE is if the chains are doubly linked and 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 keys hash to one slot and the table is a linked list with 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 . 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.
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 keys in slots is
the average chain length. With chaining can exceed 1; keys never "overflow". The next lesson shows that, under the assumption that spreads keys like a random function, an unsuccessful search costs expected time and a successful one comparisons on average. So if grows in proportion to , keeping bounded by a constant, every operation takes expected time. Tables do that by rehashing: when passes a threshold, allocate about twice as many slots and reinsert every key, which by the doubling argument costs amortized per insert.
The program fills a table with 2000 random integer keys, growing it whenever would exceed 1, and reports the chain lengths at the end.
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 : about 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 , 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 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.
#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 , 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 slots and keys. What is the load factor?
- 0.4
- 2.5
- 250
- it cannot hold more than 100 keys
What is the worst-case cost of CHAINED-SEARCH with keys?
- , if all keys hash to the same slot
Why are the chains often doubly linked?
- To search faster
- So DELETE given the element itself takes
- To store two keys per node
- To allow
In the character-sum hash, why do cat and act always collide?
- They have the same length
- Their character codes have the same sum, whatever is
- Because is prime
- They do not collide for