Kodewick
Start learning →
Open addressing19 / 52

Open addressing

Lesson 19 of 52 · Part 4 · Hash tables · about 17 minutes

Open addressing handles a collision by looking further along the same table for an empty cell, one at a time with linear probing; it slows sharply as the table fills, deletes leave a tombstone, and unordered_map uses chaining instead.

The last lesson said collisions can't be avoided: with table size 11, both 22 and 33 compute cell 0. The cheapest fix is to use no extra space: find another empty cell in the same table, and when searching, follow the same route. This is open addressing. It needs only one array and is cache-friendly; Python's dict and many high-performance hash tables use it. It also has two traps: it slows down sharply as the table fills, and you can't delete carelessly. This lesson runs each of them with a small HashTable class.

Linear probing: one cell at a time

Try number i goes to (h(k) + i) % m for i = 0, 1, 2…: if the home cell is taken, look at the next one, wrapping to 0 at the end. Each look is a probe. Table size 11, h(k) = k % 11, inserting 22 41 53 46 30 13 1 67 in order:

index 0-10, h(k) = k % 11012345678910

Linear probing - if the cell is taken, look at the next, until an empty one turns up

Searching follows the same route: compute h(k); if it's k, found; if it's another key, look at the next cell; an empty cell means k is not in the table, because when k was inserted it would have stopped at the first empty cell on this route. Finding 67 takes 4 comparisons, finding 30 takes 3.

Guess the outputA wrong guess is fine

7 18 29 40 all have k % 11 = 7. Insert 51 next: which cell does it land in, after how many probes? (prints "index probes")

1#include <iostream>2#include <vector>3using namespace std;4 5const int M = 11;6 7class HashTable {8public:9    vector<int> t;10    HashTable() : t(M, -1) {}       // -1 means empty11 12    int insert(int k) {             // returns the number of probes13        for (int i = 0; i < M; i++) {14            int p = (k % M + i) % M;15            if (t[p] == -1) { t[p] = k; return i + 1; }16        }17        return -1;18    }19};20 21int main() {22    HashTable h;23    h.insert(7); h.insert(18); h.insert(29); h.insert(40);24    int n = h.insert(51);25    for (int i = 0; i < M; i++)26        if (h.t[i] == 51) cout << i << " " << n << "\n";27    return 0;28}
Choose one

With this stage's 8 keys in place (cells 0–4 hold 22 1 46 13 67, cells 5–7 are empty, cells 8–10 hold 41 53 30), how many cells does a search for 12 look at before it knows 12 isn't there?

Exercise 1

Linear probing insert

Fill in insert - starting at k % M, find the first empty cell (-1) further along, wrapping to 0 at the end. Then print the whole table, with _ for empty cells.

It should print
_ _ 41 _ _ 18 44 59 32 22 31 73 _ 
exercise1.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5const int M = 13;6 7class HashTable {8    vector<int> t;9 10public:11    HashTable() : t(M, -1) {}12 13    void insert(int k) {14        // i from 0 to M - 1: p = (k % M + i) % M; if t[p] == -1, put k there and return15    }16 17    void show() const {18        for (int x : t)19            if (x == -1) cout << "_ "; else cout << x << " ";20        cout << "\n";21    }22};23 24int main() {25    HashTable h;26    for (int k : {18, 41, 22, 44, 59, 32, 31, 73})27        h.insert(k);28    h.show();29    return 0;30}
Output
Press Run or Ctrl+Enter

Primary clustering: the fuller, the slower

Once linear probing has placed the 8 keys 22 41 53 46 30 13 1 67 (the table from this lesson's first stage), cells 0 to 4 have merged into one run. Any new key whose h lands anywhere in 0 to 5 will stop at cell 5, so cell 5 gets picked with probability 6 / 11, while each other empty cell has 1 / 11. The longer a run, the more likely it catches the next key, and the longer it grows. This is primary clustering, linear probing's weakness: keys with different h end up in the same run, slowing each other down.

Quadratic probing spreads the steps out: tries 1, 2, 3, 4… go to h + 1², h − 1², h + 2², h − 2²… (all % m). The same 8 keys:

index 0-10, h(k) = k % 1122464153012345678910

Quadratic probing - when taken, try +1, −1, +4, −4…, so keys don't pile up cell by cell

Two keys with the same h still follow the same route under quadratic probing (secondary clustering), but keys with different h no longer queue along one run. To see how much it matters, run a table of 1019 cells: insert random keys and measure the average probes, separately for successful searches (keys in the table) and failed ones (keys not in it). The probing kind is a constructor argument:

main.cpp
1#include <cstdio>2#include <vector>3using namespace std;4 5const int M = 1019;             // a prime, and M % 4 == 3: quadratic probing can reach every cell6unsigned seed = 1;7 8unsigned next_key() {           // a home-made pseudo-random number: the same on every run, never repeats9    seed = seed * 1664525u + 1013904223u;10    return seed;11}12 13class HashTable {14    vector<unsigned> key;15    vector<bool> used;16    bool linear;                // true linear probing, false quadratic probing17 18    int probe(unsigned k, int i) const {    // where probe i goes: h, h+1, h-1, h+4, h-4 …19        long h = k % M;20        if (linear) return (h + i) % M;21        long d = (long)((i + 1) / 2) * ((i + 1) / 2);22        if (i % 2 == 0) d = -d;23        return (int)(((h + d) % M + M) % M);24    }25 26public:27    HashTable(bool lin) : key(M), used(M, false), linear(lin) {}28 29    void insert(unsigned k) {30        for (int i = 0; ; i++) {31            int p = probe(k, i);32            if (!used[p]) { used[p] = true; key[p] = k; return; }33        }34    }35 36    int search(unsigned k) const {          // returns how many cells it looked at (the empty one too)37        for (int i = 0; ; i++) {38            int p = probe(k, i);39            if (!used[p] || key[p] == k) return i + 1;40        }41    }42};43 44int main() {45    double as[] = {0.5, 0.7, 0.8, 0.9};46    printf("load    lin:found  lin:fail  quad:found  quad:fail\n");47    for (double a : as) {48        double r[4];49        for (int lin = 1; lin >= 0; lin--) {50            HashTable h(lin == 1);51            int n = (int)(a * M);52            seed = 1;53            for (int i = 0; i < n; i++) h.insert(next_key());54            long ok = 0, fail = 0;55            seed = 1;56            for (int i = 0; i < n; i++) ok += h.search(next_key());57            for (int i = 0; i < 1000; i++) fail += h.search(next_key());  // these are not in the table58            r[lin ? 0 : 2] = (double)ok / n;59            r[lin ? 1 : 3] = fail / 1000.0;60        }61        printf("  %.1f     %6.2f     %6.2f     %6.2f     %6.2f\n", a, r[0], r[1], r[2], r[3]);62    }63    return 0;64}
Output
load    lin:found  lin:fail  quad:found  quad:fail
  0.5       1.42       2.52       1.39       2.34
  0.7       2.36       6.24       1.95       4.12
  0.8       3.03      12.28       2.34       6.21
  0.9       5.79      47.53       3.05      12.99

As α goes from 0.5 to 0.9, a failed search under linear probing goes from 2.52 probes to 47.53, nearly 20 times as many; quadratic probing only reaches 12.99. In theory a failed linear-probing search takes about ½(1 + 1 / (1 − α)²) probes, 50.5 at α = 0.9, close to what we measured; it shoots up as α approaches 1. So an open-addressing table must not get too full: α is usually kept within 0.5-0.75.

MethodProbe iFlaw
linear probingh + iprimary clustering: long runs, slower as it fills
quadratic probingh + 1², h − 1², h + 2², h − 2²…may not reach every cell; needs m a prime of the form 4j + 3
double hashingh + i × h₂(k)a second hash function to compute, and h₂(k) must not be 0
Choose one

Table size 11, quadratic probing, and a key with h(k) = 8. Which cells do the first 4 tries look at, in order?

Choose one

Running this stage's program for real: as the load factor goes from 0.5 to 0.9, how do the average probes for a failed search with linear probing change, roughly?

Deleting: leave a tombstone

Take the linear-probing table again, with 22 41 53 46 30 13 1 67 placed in turn, and delete 53. The obvious idea is to empty cell 9, but 30 got to cell 10 by passing through cell 9:

index 0-10221461367415330012345678910

The wrong way - emptying cell 9 makes 30 unreachable; a tombstone is right

So each cell has three states: empty, holding a key, deleted. A search treats a tombstone as occupied and keeps walking; an insert may reuse it. Tombstones slow searches too (they have to be walked past), so when there are too many the whole table gets rebuilt.

main.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5const int M = 11;6const int EMPTY = -1;7const int DEL = -2;             // a tombstone8 9class HashTable {10    vector<int> t;11 12public:13    HashTable() : t(M, EMPTY) {}14 15    int search(int k) const {   // returns the index if found, -1 if not16        for (int i = 0; i < M; i++) {17            int p = (k % M + i) % M;18            if (t[p] == EMPTY) return -1;    // an empty cell: it can't be further on19            if (t[p] == k) return p;         // a tombstone or another key: keep going20        }21        return -1;22    }23 24    void insert(int k) {25        if (search(k) >= 0) return;          // already there26        for (int i = 0; i < M; i++) {27            int p = (k % M + i) % M;28            if (t[p] == EMPTY || t[p] == DEL) { t[p] = k; return; }   // a tombstone can be reused29        }30    }31 32    void remove_plain(int k) { int p = search(k); if (p >= 0) t[p] = EMPTY; }  // wrong33    void remove_tomb(int k)  { int p = search(k); if (p >= 0) t[p] = DEL; }    // right34 35    void show() const {36        for (int x : t)37            if (x == EMPTY) cout << "_ "; else cout << x << " ";38        cout << "\n";39    }40};41 42HashTable build() {43    HashTable h;44    for (int k : {22, 41, 53, 46, 30, 13, 1, 67})45        h.insert(k);46    return h;47}48 49int main() {50    HashTable a = build();51    a.show();52    a.remove_plain(53);53    cout << "find 30 after emptying the cell: " << a.search(30) << "\n";54    HashTable b = build();55    b.remove_tomb(53);56    cout << "find 30 after a tombstone: " << b.search(30) << "\n";57    b.insert(75);                            // 75 % 11 = 9: reuses the tombstone's cell58    cout << "insert 75: in cell " << b.search(75) << "\n";59    return 0;60}
Output
22 1 46 13 67 _ _ _ 41 53 30 
find 30 after emptying the cell: -1
find 30 after a tombstone: 10
insert 75: in cell 9

The table is just a vector<int>: no new, so nothing to delete yourself; the vector frees itself when it goes out of scope. Returning a table by value from build() is fine as well; the whole vector moves along with it.

Choose one

After deleting with tombstones, which statement is true?

Guess the outputA wrong guess is fine

3, 10 and 17 all leave remainder 3; linear probing put them in cells 3, 4 and 5. First 3 is deleted with a tombstone, then 24 is inserted (24 % 7 = 3). What does the program print?

1#include <iostream>2#include <vector>3using namespace std;4 5const int M = 7;6const int EMPTY = -1;7const int DEL = -2;8vector<int> t = {EMPTY, EMPTY, EMPTY, 3, 10, 17, EMPTY};9 10int search(int k) {11    for (int i = 0; i < M; i++) {12        int p = (k % M + i) % M;13        if (t[p] == EMPTY) return -1;14        if (t[p] == k) return p;15    }16    return -1;17}18 19void insert(int k) {20    for (int i = 0; i < M; i++) {21        int p = (k % M + i) % M;22        if (t[p] == EMPTY || t[p] == DEL) { t[p] = k; return; }23    }24}25 26int main() {27    t[search(3)] = DEL;28    insert(24);29    cout << search(24) << " " << search(17) << "\n";30    return 0;31}
Exercise 2

Searching past tombstones

In the table -1 is empty and -2 is a tombstone. Fill in search - return -1 at an empty cell; return the index when you meet k; keep going past tombstones and other keys.

It should print
10 4 -1 -1
exercise2.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5const int M = 11;6vector<int> t = {22, 1, 46, 13, 67, -1, -1, -1, 41, -2, 30};   // 53 was deleted and left a tombstone7 8int search(int k) {9    // i from 0 to M - 1: p = (k % M + i) % M; return -1 at an empty cell; return p if it is k10    return -1;11}12 13int main() {14    cout << search(30) << " " << search(67) << " " << search(53) << " " << search(19) << "\n";15    return 0;16}
Output
Press Run or Ctrl+Enter

With the STL

The STL has no open-addressing hash table. unordered_set and unordered_map use the next lesson's separate chaining: the C++ standard requires pointers and references to elements to stay valid after the table grows, and it requires per-bucket access (bucket_count() and friends), which in practice only chaining, with one separate node per key, can give. So with the STL, deleting is erase, and tombstones never come up:

main.cpp
1#include <iostream>2#include <unordered_set>3using namespace std;4 5int main() {6    unordered_set<int> s;7    for (int k : {22, 41, 53, 46, 30, 13, 1, 67})8        s.insert(k);9    cout << s.size() << " keys, " << s.bucket_count() << " buckets\n";10    s.erase(53);                             // just delete it: no tombstone11    cout << "after erasing 53: 30 is " << (s.count(30) ? "in" : "not in")12         << ", 53 is " << (s.count(53) ? "in" : "not in") << "\n";13    bool added = s.insert(30).second;        // already there: not inserted, second is false14    cout << "insert 30 again: " << (added ? "inserted" : "already there") << ", " << s.size() << " keys\n";15    return 0;16}
Output
8 keys, 13 buckets
after erasing 53: 30 is in, 53 is not in
insert 30 again: already there, 7 keys

If you want open addressing's speed, write it yourself (as in this lesson) or use a third-party library: Google's abseil flat_hash_map and Boost's unordered_flat_map are both open addressing, with the keys side by side in one array, and noticeably faster than unordered_map.

This lesson's tableunordered_set
On a collisionlook further along the arrayhang it on the bucket's chain
Search / insertO(1) on average, sharply slower at high αO(1) on average, grows itself once α passes 1
Deleteleave a tombstoneerase, removes the node
When fullyou write the growingautomatic rehash, amortised O(1)

In interviews: "How does unordered_map resolve collisions?" Separate chaining. "And Python's dict?" Open addressing. Then add open addressing's two traps: keep α below 0.75, and deletes need tombstones.

Guess the outputA wrong guess is fine

First insert a 2 that's already there, then erase a 5 that isn't. What does the program print?

1#include <iostream>2#include <unordered_set>3using namespace std;4 5int main() {6    unordered_set<int> s = {1, 2, 3};7    bool a = s.insert(2).second;8    s.erase(5);9    cout << a << " " << s.size() << "\n";10    return 0;11}
Choose one

Which of these hash tables uses open addressing?

Summary

Take-away

Open addressing: on a collision, find another empty cell in the table

  • linear probing h + i: simple, but builds long runs (primary clustering)
  • quadratic probing h ± i²: jumps apart, much less clustering
  • fuller means slower: at α = 0.9 a failed linear search takes about 47 probes; keep α below 0.75
  • deletes leave tombstones: searches walk past them, inserts may reuse them
  • the STL's unordered_set doesn't use it: it chains, and erase just deletes
1for (int i = 0; i < M; i++) {2    int p = (k % M + i) % M;3    if (t[p] == EMPTY) return -1;4    if (t[p] == k) return p;5}