Separate chaining and unordered_map
Separate chaining hangs a linked list on each cell, so colliding keys share a chain: inserting at the head is O(1), a search compares α = n / m keys on average, and unordered_map rehashes once load_factor() passes 1.
Open addressing packs every key into one array, slows down when the table fills and needs tombstones to delete. A more direct idea: each cell holds not a key but the head pointer of a linked list, and every key that computes that index hangs on its chain. This is separate chaining. C++'s unordered_map, Java's HashMap and Go's map before 1.24 all work this way. It uses chapter 1's linked lists: insertion is head insertion, deletion is deleting a node.
Buckets and chains
Allocate an array of m pointers, vector<Node*> head(m, nullptr). To insert k: compute s = k % m, new a node and put it at the front of head[s] (head insertion, O(1), no walk to the tail). To find k: compute s and compare along the chain head[s] one node at a time.
Again table size 11 and last lesson's 8 keys 22 41 53 46 30 13 1 67:
Compared with open addressing, colliding keys queue only with keys in their own bucket: they never take another key's cell, so there is no clustering.
1#include <iostream>2#include <vector>3using namespace std;4 5const int M = 11;6 7struct Node {8 int key;9 Node* next;10 Node(int k, Node* n) : key(k), next(n) {}11};12 13class HashTable {14 vector<Node*> head;15 16public:17 HashTable() : head(M, nullptr) {}18 19 ~HashTable() { // every node on every chain was new'd: delete them one by one20 for (Node* p : head)21 while (p) {22 Node* nx = p->next;23 delete p;24 p = nx;25 }26 }27 28 void insert(int k) {29 int s = k % M;30 head[s] = new Node(k, head[s]); // head insertion: the new node points at the old first one31 }32 33 bool search(int k, int& cmp) const { // cmp counts the comparisons34 cmp = 0;35 for (Node* p = head[k % M]; p; p = p->next) {36 cmp++;37 if (p->key == k) return true;38 }39 return false;40 }41 42 void remove(int k) {43 Node** pp = &head[k % M]; // points at "the pointer that points at the current node"44 while (*pp && (*pp)->key != k)45 pp = &(*pp)->next;46 if (*pp) {47 Node* dead = *pp;48 *pp = dead->next; // the one before now points at the one after49 delete dead;50 }51 }52 53 void show() const {54 for (int i = 0; i < M; i++) {55 if (!head[i]) continue;56 cout << i << ":";57 for (Node* p = head[i]; p; p = p->next)58 cout << " " << p->key;59 cout << "\n";60 }61 }62};63 64int main() {65 HashTable h;66 for (int k : {22, 41, 53, 46, 30, 13, 1, 67})67 h.insert(k);68 h.show();69 int c;70 bool f = h.search(41, c);71 cout << "find 41: " << (f ? "yes" : "no") << ", " << c << " comparisons\n";72 f = h.search(19, c);73 cout << "find 19: " << (f ? "yes" : "no") << ", " << c << " comparisons\n";74 h.remove(30);75 h.search(41, c);76 cout << "find 41 after deleting 30: " << c << " comparisons\n";77 return 0;78}
0: 22 1: 67 1 2: 13 46 8: 30 41 9: 53 find 41: yes, 2 comparisons find 19: no, 2 comparisons find 41 after deleting 30: 1 comparisons
Deleting is an ordinary linked-list delete, and the other keys are still found afterwards: no tombstones needed. The pointer-to-pointer pp makes deleting the first node and a middle node the same code, with no special case for the head. The nodes are all new'd, so the destructor ~HashTable() walks every chain and deletes them; it runs by itself when the table goes out of scope at the end of main.
Insert 5 12 3 19 26 in order (head insertion). What does bucket 5's chain print, head to tail?
1#include <iostream>2#include <vector>3using namespace std;4 5struct Node {6 int key;7 Node* next;8 Node(int k, Node* n) : key(k), next(n) {}9};10 11int main() {12 const int M = 7;13 vector<Node*> head(M, nullptr);14 for (int k : {5, 12, 3, 19, 26})15 head[k % M] = new Node(k, head[k % M]); // head insertion16 for (Node* p = head[5]; p; p = p->next)17 cout << p->key << " ";18 cout << "\n";19 for (Node* p : head)20 while (p) { Node* nx = p->next; delete p; p = nx; }21 return 0;22}
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 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.
Node* p = new Node;p->key = k;head[s] = p;p->next = head[s];
15 8 1
p->next = head[s]), then the bucket points at the new node (head[s] = p). The other way round, head[s] is already p, so p->next points at itself. p->key = k can go anywhere after the new.Building with head insertion
✓Fill in the head insertion and the printing - table size 7, h(k) = k % 7, one line bucket: key key … per non-empty bucket.
1: 1 22 15 2: 16 30 9 4: 4
1#include <iostream>2#include <vector>3using namespace std;4 5struct Node {6 int key;7 Node* next;8 Node(int k, Node* n) : key(k), next(n) {}9};10 11int main() {12 const int M = 7;13 vector<Node*> head(M, nullptr);14 for (int k : {15, 22, 9, 30, 1, 16, 4}) {15 // head insertion: head[k % M] = new Node(k, head[k % M]);16 }17 for (int i = 0; i < M; i++) {18 if (!head[i]) continue;19 cout << i << ":";20 // walk head[i] and print each key with a space before it21 cout << "\n";22 }23 for (Node* p : head)24 while (p) { Node* nx = p->next; delete p; p = nx; }25 return 0;26}
Deleting a key
✓Fill in remove - find k on its chain, make the pointer before it point at the one after it, then delete it. With the pointer-to-pointer pp the head needs no special case.
1: 22 15 8 1 1: 15 1
1#include <iostream>2#include <vector>3using namespace std;4 5const int M = 7;6 7struct Node {8 int key;9 Node* next;10 Node(int k, Node* n) : key(k), next(n) {}11};12 13vector<Node*> head(M, nullptr);14 15void insert(int k) {16 head[k % M] = new Node(k, head[k % M]);17}18 19void remove(int k) {20 Node** pp = &head[k % M];21 // while *pp isn't nullptr and isn't k: pp = &(*pp)->next; if found: keep it, *pp = its next, delete it22}23 24void show(int s) {25 cout << s << ":";26 for (Node* p = head[s]; p; p = p->next)27 cout << " " << p->key;28 cout << "\n";29}30 31int main() {32 for (int k : {1, 8, 15, 22})33 insert(k);34 show(1);35 remove(22); // the head36 remove(8); // a middle node37 remove(50); // not in the table38 show(1);39 for (Node* p : head)40 while (p) { Node* nx = p->next; delete p; p = nx; }41 return 0;42}
The average chain length is α
Spread n keys over m buckets with a hash function that spreads evenly, and each bucket holds n / m = α keys on average. So:
- a failed search walks a whole chain: α comparisons on average;
- a successful search walks a little over half a chain: about 1 + α / 2 comparisons.
α no longer has to stay below 1: a chain can be any length. But a large α means long chains and slow searches; as long as α is a constant, search is O(1). So a chaining table grows too: once α passes a threshold (1 here, the same as unordered_map) it allocates a new table of about 2m and moves each key across, computing its index from the new m.
You can't just move each old chain across whole: the index is k % m, so when m changes every key's index must be computed again. The nodes themselves are not new'd again; only their next changes as they are hung on the new table's chains. One resize costs O(n), but each one doubles the table, so it rarely happens. Run it with 1000 random keys, starting at m = 7 and growing whenever α would pass 1:
1#include <cstdio>2#include <vector>3using namespace std;4 5struct Node {6 unsigned key;7 Node* next;8 Node(unsigned k, Node* n) : key(k), next(n) {}9};10 11unsigned seed = 1;12unsigned next_key() { // a home-made pseudo-random number: the same on every run13 seed = seed * 1664525u + 1013904223u;14 return seed;15}16 17bool is_prime(int x) {18 for (int d = 2; d * d <= x; d++)19 if (x % d == 0) return false;20 return true;21}22 23class HashTable {24 vector<Node*> head;25 int n = 0;26 27 void rehash() {28 int m = head.size(), m2 = 2 * m + 1;29 while (!is_prime(m2)) m2++; // a prime near 2m30 vector<Node*> h2(m2, nullptr);31 for (Node* p : head)32 while (p) {33 Node* nx = p->next; // remember the next one first34 int s = p->key % m2; // compute the index again with the new size35 p->next = h2[s];36 h2[s] = p;37 p = nx;38 moved++;39 }40 printf("grow: %4d -> %4d (moved %d keys)\n", m, m2, n);41 head.swap(h2); // switch to the new table; the old vector frees itself42 }43 44public:45 int moved = 0;46 47 HashTable(int m) : head(m, nullptr) {}48 49 ~HashTable() {50 for (Node* p : head)51 while (p) { Node* nx = p->next; delete p; p = nx; }52 }53 54 void insert(unsigned k) {55 if (n + 1 > (int)head.size()) rehash(); // inserting would push α past 1: grow first56 int s = k % head.size();57 head[s] = new Node(k, head[s]);58 n++;59 }60 61 void report() const {62 int m = head.size(), longest = 0, empty = 0;63 for (Node* p : head) {64 int len = 0;65 for (; p; p = p->next) len++;66 if (len > longest) longest = len;67 if (len == 0) empty++;68 }69 printf("n = %d, m = %d, α = %.2f\n", n, m, (double)n / m);70 printf("longest chain %d, empty buckets %d\n", longest, empty);71 printf("%d moves in all, %.2f per key on average\n", moved, (double)moved / n);72 }73};74 75int main() {76 HashTable h(7);77 for (int i = 0; i < 1000; i++)78 h.insert(next_key());79 h.report();80 return 0;81}
grow: 7 -> 17 (moved 7 keys) grow: 17 -> 37 (moved 17 keys) grow: 37 -> 79 (moved 37 keys) grow: 79 -> 163 (moved 79 keys) grow: 163 -> 331 (moved 163 keys) grow: 331 -> 673 (moved 331 keys) grow: 673 -> 1361 (moved 673 keys) 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 moved keys 1307 times in all, 1.31 times per key on average: 7 + 17 + 37 + … + 673, each term about double the one before, adds up to less than twice the last term, so less than 2n. This is the amortised O(1) from chapter 1's doubling vector. The longest chain holds only 5 and nearly half the buckets are empty, which is what random spreading normally looks like.
n = 20 keys spread evenly over m = 8 buckets. How many comparisons does a failed search take on average?
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 addressing | Separate chaining | |
|---|---|---|
| On a collision | find another empty cell in the table | hang it on the same chain |
| Can α exceed 1 | no, it slows clearly above 0.75 | yes, the average chain length is α |
| Clustering | linear probing has primary clustering | none, keys queue only within their bucket |
| Deleting | needs tombstones | delete the node |
| Extra space | no pointers, but empty cells to spare | one next pointer per key |
| Cache | good: side by side in one array | poor: nodes scattered on the heap, pointer hops |
| Who uses it | Python dict, Go's map since 1.24 | Java HashMap, C++ unordered_map |
Few keys, speed matters, few deletes: open addressing. Unknown number of keys, frequent deletes: chaining. Java's HashMap goes one step further: once a chain reaches 8 nodes it becomes a red-black tree (chapter 6's balanced trees), so even the worst case is O(log n).
In exams: chaining questions usually give h(k) and the table size, ask you to draw each chain (watch whether it's head or tail insertion), and then compute the ASL for successful and failed searches: successful is the sum of each key's position on its chain divided by n, failed is the sum of the chain lengths divided by m (the usual convention doesn't count the comparison with the null pointer).
When is chaining the better choice?
Which statements about chaining are true? (You can pick more than one.)
With the STL
unordered_set<K> and unordered_map<K, V> are this lesson's table: a row of buckets, one node per key, colliding keys hung together. g++'s implementation threads all the nodes on one singly linked list, and each bucket only remembers "where my stretch of it starts", so walking the whole table is walking that list. The maximum load factor is 1 by default: as soon as there are more keys than buckets, it switches to a prime bucket count about twice as big and every key computes its bucket again. Run it and watch it grow:
1#include <iostream>2#include <unordered_set>3using namespace std;4 5int main() {6 unordered_set<int> s;7 size_t last = s.bucket_count();8 cout << "empty: " << last << " bucket\n";9 for (int k = 0; k < 1000; k++) {10 s.insert(k);11 if (s.bucket_count() != last) { // the bucket count changed: it just rehashed12 last = s.bucket_count();13 cout << "key " << s.size() << " grew it to " << last << " buckets, α = " << s.load_factor() << "\n";14 }15 }16 cout << "at the end: " << s.size() << " keys, α = " << s.load_factor() << "\n";17 return 0;18}
empty: 1 bucket key 1 grew it to 13 buckets, α = 0.0769231 key 14 grew it to 29 buckets, α = 0.482759 key 30 grew it to 59 buckets, α = 0.508475 key 60 grew it to 127 buckets, α = 0.472441 key 128 grew it to 257 buckets, α = 0.498054 key 258 grew it to 541 buckets, α = 0.476895 key 542 grew it to 1109 buckets, α = 0.488729 at the end: 1000 keys, α = 0.901713
An empty table has 1 bucket, and the first key opens 13. After that the bucket count goes 13, 29, 59, 127, 257, 541, 1109: roughly doubling each time, and always a prime. Key 14 would make α 14 / 13 > 1, so the table grows to 29 first. As with the hand-written table, a resize costs O(n) and insertion stays amortised O(1). If you know roughly how many keys are coming, call reserve(n) first and it never has to grow.
The unordered_map operations you use most:
1#include <iostream>2#include <string>3#include <vector>4#include <algorithm>5#include <unordered_map>6using namespace std;7 8int main() {9 unordered_map<string, int> age;10 age["amy"] = 20;11 age["bob"] = 31;12 age.insert({"cat", 25});13 age["amy"]++; // there already: change it14 cout << age["amy"] << " " << age.count("dan") << "\n";15 16 auto it = age.find("bob"); // an iterator to it if found, end() if not17 if (it != age.end())18 cout << it->first << " " << it->second << "\n";19 20 cout << age["dan"] << ", size = " << age.size() << "\n"; // [] puts in a 0 when the key is missing21 age.erase("dan");22 23 vector<string> names; // the iteration order is not fixed: take them out and sort first24 for (const auto& kv : age)25 names.push_back(kv.first);26 sort(names.begin(), names.end());27 for (const string& n : names)28 cout << n << "=" << age[n] << " ";29 cout << "\n";30 return 0;31}
21 0 bob 31 0, size = 4 amy=21 bob=31 cat=25
age["dan"] was only meant to take a look, yet it put dan = 0 into the table and the size went from 3 to 4. To ask whether a key is there, use count or find. The order you walk an unordered_map in depends on the buckets and may change with another compiler or one more key; to print in order, sort first, or use map instead.
| Operation | unordered_map | map (red-black tree) |
|---|---|---|
m[k], insert, find, count, erase | O(1) on average, O(n) worst case | O(log n) |
| growing (rehash) | O(n) each time, amortised O(1) | never needed |
| iteration order | not fixed | by key, smallest first |
| what the key needs | hash and == | < |
Press Visualize here and step through: h is drawn as its row of buckets. Of the 13 buckets, 29, 16 and 3 all land in bucket 3 (29 % 13 = 3, 16 % 13 = 3) and hang in one chain:
1#include <iostream>2#include <unordered_map>3using namespace std;4 5int main() {6 unordered_map<int, int> h;7 int keys[] = {3, 16, 29, 5, 8};8 for (int k : keys) h[k] = k * 10;9 cout << h.size() << " " << h.bucket_count() << " " << h[29] << "\n";10 return 0;11}
5 13 290
In interviews: "When does unordered_map degrade to O(n)?" When every key lands in the same bucket. g++ hashes integers as k % a prime bucket count, and people build sequences of integers that all hit one bucket to break it (anti-hash tests in programming contests). Need order or a guaranteed worst case: map. Need speed and don't care about order: unordered_map, plus a reserve.
The map only has a. First count asks whether b is there, then m["b"] reads it. What does the program print?
1#include <iostream>2#include <string>3#include <unordered_map>4using namespace std;5 6int main() {7 unordered_map<string, int> m;8 m["a"] = 1;9 cout << m.count("b") << " ";10 int x = m["b"];11 cout << m.size() << " " << x << "\n";12 return 0;13}
count("b") only asks: b isn't there, so it returns 0. m["b"] is different: when the key is missing it first puts in b = 0, then hands that 0 to x. So the map now has 2 keys and x is 0. To just check whether a key is there, use count or find.When does a lookup in an unordered_map slow down to O(n)?
reserve only means fewer rehashes.Summary
Separate chaining: a linked list in every bucket
- head[m] is a row of list heads; colliding keys share a chain, head insertion is O(1)
- search: compute the index, compare along the chain; average chain length = α = n / m
- deleting is deleting a list node, no tombstones; α may exceed 1
- once α passes 1, grow to about 2m and compute every key's index from the new m, amortised O(1)
- unordered_map is exactly this: O(1) on average, no fixed order, [] inserts missing keys
1int s = k % M;2head[s] = new Node(k, head[s]);3for (Node* p = head[s]; p; p = p->next)4 if (p->key == k) return true;5return false;