What is a hash table

A hash table is a data structure that stores key-value pairs and lets you retrieve any value in average time, however many entries it holds. Average is the important word: almost every operation finds its key in a step or two, and the rare ones that don't are covered in the worst case further down.

The key-value model is familiar from a phonebook. To find Alice's number, you don't scan every name from A to Z; you flip to the right section and find her there. A hash table does the same in software: it calculates where to look instead of searching through every stored entry.

The phonebook analogy

A phonebook with 10,000 entries. You want Alice's number.

  • Scanning every entry: O(n), up to 10,000 comparisons
  • Flipping to "A" then scanning: still O(n), just a smaller fraction
  • A hash table: compute hash("Alice") → slot 412 and go directly there, in one lookup

The hash function turns the key into a precise location.

A hash table is a concrete data structure that implements the Map ADT (also called Dictionary). The Map ADT defines the contract: store a value under a key, retrieve a value by key, delete a key. A hash table is one way to honor that contract. An ordered tree is another. A hash table wins on average-case speed but gives up ordering, which the last sections come back to.

The problem previous structures couldn't solve

Every structure in this series so far gives you something but takes something away.

Arrays offer O(1) access, but only by integer index. To look up a user by username you'd need that user's exact position in the array, which you don't know. You'd end up storing users[0], users[1] and so on, then scanning for the right one, which is O(n).

Linked lists are flexible but require traversal. Finding a node by value means walking the chain from the head, which is O(n) in the worst case.

Neither structure can answer the question: "What is Alice's phone number?" efficiently, because neither can map an arbitrary string key to a stored value in constant time.

Hash tables extend the O(1) random access that arrays give integer indices to any key type (strings, integers, composite objects) by computing the integer index from the key.

nO(n)O(1)
1001001
10,00010,0001
1,000,0001,000,0001

Hash functions

A hash function takes a key and produces an integer index in the range [0, m-1], where m is the number of buckets in the table. Two properties make a hash function useful:

  • Determinism: the same key always produces the same index
  • Uniform distribution: keys spread evenly across all buckets, so no single bucket gets overloaded

djb2 is a simple, widely used string hash function:

C
unsigned int hash(const char *key, int table_size) {    unsigned long h = 5381;    int c;    while ((c = *key++))        h = ((h << 5) + h) + c;  /* h * 33 + c */    return h % table_size;}

With a table of 8 buckets, this maps our three keys like this:

Trace
hash("name", 8) → 3hash("age",  8) → 6hash("city", 8) → 1
After inserting "city"→"Paris", "name"→42, "age"→30
[0]NULL
[1]"city""Paris"NULL
[2]NULL
[3]"name"42NULL
[4]NULL
[5]NULL
[6]"age"30NULL
[7]NULL

Three keys map to three different slots, each read directly without scanning

To look up "name", the table hashes the key to slot 3 and reads from there, without comparing it against other entries or traversing anything.

A list of keys is not a hash table

Suppose you skip the hash function and keep the pairs in a list, finding a key by comparing strings until one matches:

C
struct Pair {    const char *key;    int         value;};int get(const struct Pair *pairs, int n, const char *key, int *out) {    for (int i = 0; i < n; i++) {        if (strcmp(pairs[i].key, key) == 0) {            *out = pairs[i].value;            return 1;        }    }    return 0;}

This still stores values under string keys and gives them back, so it honors the Map ADT. It is not a hash table, because nothing computes where a key lives, and that step from key to index is where a hash table's O(1) comes from. Here every lookup compares against the entries one by one, which is O(n). The structure has a name, an association list, and for a handful of keys it can even be faster than a hash table, since comparing three short strings can cost less than hashing one.

What hashing a key costs

The O(1) counts entries: the table does the same work whether it holds ten keys or ten million. It says nothing about the size of the key. djb2 runs its loop once per character, so hashing a key of length k costs O(k), and a lookup that finds the key compares it once more, character by character, for another O(k). A 20-character username costs about 20 steps in a table of a hundred entries and in a table of a hundred million. Since k doesn't grow with the table, the analysis treats it as a constant.

So a slow hash function doesn't break the O(1) by itself. One that is O(k) in the key keeps the table O(1) in the number of entries, and each operation just costs more. A hash function whose work grows with the number of entries, like one that scanned the table to choose a slot, makes every operation O(n), no faster than walking a list. Long keys do cost something in practice, which is why Java's String computes its hashCode() the first time it's asked and stores it in the object.

What can be used as a key

A hash function must be deterministic: the same key always produces the same hash. That limits which types can be keys. A key must be immutable, or at least stay unchanged for as long as it is in the table.

If you insert a key and then mutate it, its hash changes, but the entry still sits in the bucket for the old hash. Lookups hash the new key to a different bucket and find nothing, so the entry stays in the table, unreachable, without ever having been deleted.

Most languages enforce this constraint either statically or at runtime:

Python requires keys to implement __hash__ and raises TypeError at insertion time if they don't. The immutable built-in types work: str, int, float, tuple (of hashables) and frozenset. Mutable types (list, dict, set) are unhashable by design:

Python
d = {}d["name"] = "Alice"    # ✓ str is immutabled[(1, 2)] = "point"    # ✓ tuple of ints is immutabled[[1, 2]] = "point"    # ✗ TypeError: unhashable type: 'list'

Java allows any Object as a key, since every object has a hashCode() method. Nothing stops you from using a mutable one, and when it goes wrong it fails silently:

Java
List<String> key = new ArrayList<>(List.of("a", "b"));map.put(key, 42);   // inserted at hash of ["a", "b"]key.add("c");       // mutated — hash changes silentlymap.get(key);       // returns null — entry is unreachable

JavaScript's Map accepts any value as a key, objects included, and compares objects by reference identity. Two distinct objects with the same fields are different keys:

JavaScript
const map = new Map()const key = { x: 1 }map.set(key, 'value')map.get({ x: 1 }) // undefined — different object referencemap.get(key) // "value" — same reference

C++'s std::unordered_map requires a std::hash<K> specialization. Primitive types and std::string are supported out of the box; custom types must provide one explicitly, which forces you to define what constitutes the key's identity.

Rust enforces this at compile time: key types must implement both Hash and Eq. The standard library does not implement Hash for types with mutable interior state, so the type system enforces the constraint.

In practice, use immutable values as keys. Strings and integers are safe everywhere. If you need a composite or custom type as a key, make sure the fields that feed the hash never change after insertion.

Collisions are inevitable

A table with 8 buckets has only 8 slots, so a 9th key has to share a slot with another one. Collisions show up well before that, too, because spreading keys randomly doesn't give each one its own slot:

Trace
hash("name", 8) → 3hash("make", 8) → 3   ← collision — same slot as "name"

Any hash function that maps an unbounded set of keys into a bounded range will eventually produce the same index for two different keys, so every hash table needs a way to handle collisions. The two dominant strategies are chaining and open addressing.

Collision resolution: chaining

In chaining, each bucket holds a linked list of entries. When two keys hash to the same slot, their entries both live in the list at that bucket. Lookup must scan the list to find the right key.

C
#define TABLE_SIZE 8struct Entry {    char         *key;    int           value;    struct Entry *next;};struct HashTable {    struct Entry *buckets[TABLE_SIZE];};void ht_init(struct HashTable *ht) {    for (int i = 0; i < TABLE_SIZE; i++)        ht->buckets[i] = NULL;}unsigned int hash(const char *key) {    unsigned long h = 5381;    int c;    while ((c = *key++))        h = ((h << 5) + h) + c;    return h % TABLE_SIZE;}
C
void ht_insert(struct HashTable *ht, const char *key, int value) {    unsigned int idx = hash(key);    /* Key already exists — update in place */    struct Entry *curr = ht->buckets[idx];    while (curr) {        if (strcmp(curr->key, key) == 0) {            curr->value = value;            return;        }        curr = curr->next;    }    /* New key — prepend to chain */    struct Entry *entry = malloc(sizeof(struct Entry));    entry->key   = strdup(key);    entry->value = value;    entry->next  = ht->buckets[idx];    ht->buckets[idx] = entry;}int ht_lookup(struct HashTable *ht, const char *key, int *out) {    unsigned int idx = hash(key);    struct Entry *curr = ht->buckets[idx];    while (curr) {        if (strcmp(curr->key, key) == 0) {            *out = curr->value;            return 1;  /* found */        }        curr = curr->next;    }    return 0;  /* not found */}void ht_delete(struct HashTable *ht, const char *key) {    unsigned int idx = hash(key);    struct Entry *curr = ht->buckets[idx];    struct Entry *prev = NULL;    while (curr) {        if (strcmp(curr->key, key) == 0) {            if (prev) prev->next = curr->next;            else      ht->buckets[idx] = curr->next;            free(curr->key);            free(curr);            return;        }        prev = curr;        curr = curr->next;    }}

"make" hashes to slot 3, which "name" already occupies, so ht_insert prepends it to the chain:

insert("make", 17): collision at slot 3

hash("make") → slot 3

[0]NULL
[1]"city""Paris"NULL
[2]NULL
[3]"make"17"name"42NULL
[4]NULL
[5]NULL
[6]"age"30NULL
[7]NULL

Both "make" and "name" live at slot 3, linked together in a chain

Looking up "name" now means hashing to slot 3 and walking the chain, comparing keys until one matches. With a good hash function and a low load factor, chains stay short, usually one or two entries.

Chaining operation costs:

OperationAverageWorst caseWhy
insertO(1)O(n)Hash key, prepend to chain; worst if all n keys land in the same bucket
lookupO(1)O(n)Hash key, scan chain for match; worst if all n keys share a bucket
deleteO(1)O(n)Hash key, unlink node from chain; worst if all n keys share a bucket

Insert, look up and delete keys, and watch each one run: the hash adds one letter at a time, the % picks the slot, and the walk compares keys along that slot's chain. This playground swaps djb2 for a hash you can check in your head, the sum of each letter's position in the alphabet (cat is 3 + 1 + 20), because djb2 multiplies by 33 per character and a two-letter key already reaches seven digits. It also uses 5 buckets instead of 8, so a collision is only a few keys away. Either way, the collision comes from the mod.

It's a deliberately bad hash function, which makes it a useful one to poke at. Try dog and key: 26 and 41 are different numbers that both land in slot 1. Then try ab and ba: the same letters in any order sum to the same value, so the hash can never tell them apart, and the uniform distribution property fails.

Hash table with chaining3 entries in 5 slots
k11
e5
y25
h = 041 % 5 = 1
[0]
[1]
dog9
[2]
[3]
[4]
sun17
cat5
100%
Operation log
  1. every step of the next run shows up here
0/0

insert, look up or delete a key: each one hashes it letter by letter, then walks the chain

Collision resolution: open addressing

Open addressing stores every entry in the flat array itself, with no linked lists or separate allocations. On a collision, the table probes for the next empty slot.

The simplest strategy is linear probing: if slot i is taken, try i+1, then i+2, wrapping around with modulo.

C
#define TABLE_SIZE 8#define DELETED    ((char *)-1)  /* tombstone sentinel */struct Slot {    char *key;    int   value;};struct HashTable {    struct Slot slots[TABLE_SIZE];};void ht_init(struct HashTable *ht) {    for (int i = 0; i < TABLE_SIZE; i++)        ht->slots[i].key = NULL;}void ht_insert(struct HashTable *ht, const char *key, int value) {    unsigned int idx = hash(key) % TABLE_SIZE;    for (int i = 0; i < TABLE_SIZE; i++) {        unsigned int probe = (idx + i) % TABLE_SIZE;        char *k = ht->slots[probe].key;        if (k == NULL || k == DELETED) {            ht->slots[probe].key   = strdup(key);            ht->slots[probe].value = value;            return;        }        if (strcmp(k, key) == 0) {            ht->slots[probe].value = value;  /* update */            return;        }    }    /* table is full */}int ht_lookup(struct HashTable *ht, const char *key, int *out) {    unsigned int idx = hash(key) % TABLE_SIZE;    for (int i = 0; i < TABLE_SIZE; i++) {        unsigned int probe = (idx + i) % TABLE_SIZE;        char *k = ht->slots[probe].key;        if (k == NULL) return 0;  /* empty slot: key not in table */        if (k != DELETED && strcmp(k, key) == 0) {            *out = ht->slots[probe].value;            return 1;        }    }    return 0;}

Deletion requires care. Suppose "make" collided at slot 3 (already occupied by "name") and linear probing placed it at slot 4. After deleting "name", the naive approach of setting slots[3].key = NULL silently breaks lookups for any key that was displaced past that slot. A later lookup for "make" hashes to 3, sees an empty slot and reports "not found", even though "make" is right there at slot 4.

The fix is to mark the slot with a tombstone sentinel instead of clearing it. Lookups skip tombstones and keep probing; insertions may reuse them.

Naive removal (slots[3] = NULL)

[0]
[1]"city""Paris"
[2]
1. stop[3]
[4]"make"17
[5]
[6]"age"30
[7]

Tombstone (slots[3] = DELETED)

[0]
[1]"city""Paris"
[2]
1. skip[3]DELETED
2. found[4]"make"17
[5]
[6]"age"30
[7]

lookup("make"): the left table stops at the empty slot and returns not-found; the right one skips the tombstone and finds it

C
void ht_delete(struct HashTable *ht, const char *key) {    unsigned int idx = hash(key) % TABLE_SIZE;    for (int i = 0; i < TABLE_SIZE; i++) {        unsigned int probe = (idx + i) % TABLE_SIZE;        char *k = ht->slots[probe].key;        if (k == NULL) return;  /* key not in table */        if (k != DELETED && strcmp(k, key) == 0) {            free(ht->slots[probe].key);            ht->slots[probe].key = DELETED;  /* tombstone */            return;        }    }}

Alternative: backward shift deletion. Tombstones are lazy: they put off the cleanup. Backward shift deletion repairs the probe chain right away, so no sentinel is needed. After clearing the deleted slot, the algorithm walks forward and pulls back any displaced key that would become unreachable.

A key at position j is "displaced" (placed there by probing past its home slot) if its home falls at or before the hole. Moving it back one step closes the gap without breaking any probe chain.

C
void ht_delete(struct HashTable *ht, const char *key) {    unsigned int idx = hash(key) % TABLE_SIZE;    int hole = -1;    for (int i = 0; i < TABLE_SIZE; i++) {        unsigned int probe = (idx + i) % TABLE_SIZE;        if (ht->slots[probe].key == NULL) return;   /* not found */        if (strcmp(ht->slots[probe].key, key) == 0) {            free(ht->slots[probe].key);            ht->slots[probe].key = NULL;            hole = probe;            break;        }    }    if (hole == -1) return;    /* Shift displaced keys back into the hole */    for (;;) {        unsigned int j    = (hole + 1) % TABLE_SIZE;        unsigned int home = hash(ht->slots[j].key) % TABLE_SIZE;        /* Stop at an empty slot — the chain ends here */        if (ht->slots[j].key == NULL) break;        /* Check whether the key at j was displaced past the hole.           If home is NOT strictly between hole and j (cyclically),           the key needs the hole to be reachable — pull it back. */        int displaced = (home <= (unsigned int)hole)                      || (home > j && j < (unsigned int)hole);        if (!displaced) { hole = j; continue; }        ht->slots[hole] = ht->slots[j];        ht->slots[j].key = NULL;        hole = j;    }}

Lookups no longer have tombstones to skip, but deletion becomes more complex and slightly slower. The Robin Hood row in the comparison further down mentions this interaction: deletion-heavy workloads make tombstone logic expensive, and backward shift avoids it.

ApproachDeletion costLookup after deletionTombstone buildup
TombstoneO(1)Skips tombstones (slightly slower)Yes, needs periodic rehash
Backward shiftO(n) worstNo overheadNo

For most workloads dominated by lookups and inserts with occasional deletes, tombstones win on simplicity. For deletion-heavy workloads where clean lookup performance matters, backward shift is worth the extra deletion cost.

Linear probing is the simplest of three open addressing strategies, which differ in how they compute the next slot to try after a collision.

Linear probing advances by a fixed step of 1 on every collision:

Trace
probe(i) = (h(key) + i) % m
Trace
Table size m=11, h(key)=3:  i=0 → 3  i=1 → 4  i=2 → 5  i=3 → 6   ← consecutive run; primary clustering grows here

The sequential probe pattern is cache-friendly, since all candidates are adjacent in memory, but it causes primary clustering: occupied slots merge into long runs that make future insertions slower.


Quadratic probing advances by i² on the i-th collision:

Trace
probe(i) = (h(key) + i²) % m
Trace
Table size m=11, h(key)=3:  i=0 → 3  i=1 → 4  (3 + 1)  i=2 → 7  (3 + 4)  i=3 → 1  (3 + 9) % 11  i=4 → 8  (3 + 16) % 11   ← scattered; no long consecutive run

The scattered pattern breaks primary clustering, but two keys that hash to the same initial slot still follow the same probe sequence, which is called secondary clustering. For quadratic probing to visit all m slots (guaranteeing insertion never fails on a non-full table), m must be prime and α must stay below 0.5.


Double hashing computes the step from a second hash function:

Trace
probe(i) = (h1(key) + i × h2(key)) % m
Trace
Table size m=11, h1(key)=3, h2(key)=4:  i=0 →  3  (3 + 0×4)  i=1 →  7  (3 + 1×4)  i=2 →  0  (3 + 2×4) % 11  i=3 →  4  (3 + 3×4) % 11   ← step differs per key; nothing shared

Two keys that collide at the same initial slot diverge after the first probe because they have different h2 values. That removes both primary and secondary clustering and gives the best distribution of the three, at the cost of two hash computations per probe. The second function must never return 0, because a zero step locks the probe in place. The standard formula h2(key) = p - (h1(key) % p) for a small prime p guarantees this:

C
unsigned int h2(const char *key, int p) {    return p - (djb2(key) % p);  /* p is a small prime, e.g. 7 */}unsigned int probe_slot(const char *key, int i, int m, int p) {    return (h1(key) + i * h2(key, p)) % m;}

Robin Hood hashing is a refinement on top of linear probing and has no probe formula of its own. During insertion, if the candidate slot holds a key whose probe length (distance from its home slot) is shorter than the inserted key's, the two swap, and the displaced key continues probing from that point. This "steal from the rich, give to the poor" policy evens out probe lengths across the table and lowers their variance. Rust's HashMap used Robin Hood hashing until switching to Swiss Tables (a SIMD-accelerated flat layout) in 2019, with Rust 1.36.


When to choose each:

StrategyUse whenAvoid when
Linear probingCache performance is the priority; α stays below 0.5Heavy load or adversarial key distributions
Quadratic probingYou want less clustering with minimal complexity; m is primeα approaches 0.5; non-prime table sizes
Double hashingDistribution quality matters most; higher load factors neededTwo hash computations per probe are too expensive
Robin HoodYou want linear-probing cache benefits with lower varianceDeletion-heavy workloads (tombstone logic interacts poorly)

Open addressing operation costs:

OperationAverageWorst caseWhy
insertO(1)O(n)Hash key, probe a few slots; worst under severe clustering or a nearly full table
lookupO(1)O(n)Hash key, probe until key or empty slot found; worst under severe clustering
deleteO(1)O(n)Probe to locate key, place tombstone; same probe cost as lookup

The same hash, the same 5 slots and the same starting keys as the chaining playground, now stored in the array itself. sun already shows a collision: its home is slot 4, taken by cat, so it probed on and wrapped around to slot 0. Insert key and watch it probe past dog. Then delete cat and look up sun again: the lookup skips the tombstone in slot 4 and still finds it. Keep inserting new keys until all five slots are taken: the next one probes every slot and has nowhere to go, which chaining never runs into.

Hash table with linear probing3/5 keys · 0 tombstones
k11
e5
y25
h = 041 % 5 = 1
0x2000sun170
0x2004dog91
0x20082
0x200C3
0x2010cat54
100%
Operation log
  1. every step of the next run shows up here
0/0

insert, look up or delete: each one hashes the key, then probes slot by slot from its home

Chaining vs. open addressing at a glance:

ChainingOpen addressing (linear probing)
Memory layoutLinked nodes (scattered)Flat array (contiguous)
Cache performancePoor: pointer chasingGood: sequential memory
Max load factorAny (just slower)Must stay below ~0.7
DeleteRelink chainTombstone required
Implementation complexityMore pointer bookkeepingSimpler array arithmetic

Which one runs in practice

Both strategies date back to the first hash tables, in the 1950s, and both ship in languages you use today, but which one dominated has changed over time. In both, a slot stores the key next to the value. A slot only tells you which keys could be there, and comparing the stored key is how a lookup knows it found the right one.

When hash tables became standard library types, chaining won. Java's Hashtable (1996) and HashMap (1998), and the std::unordered_map that C++ standardized in 2011, all hang a linked list off each bucket. It's simple, it keeps working at high load factors, and deleting a key just unlinks a node, with no tombstones. Python's dict was the notable exception, using open addressing from the start. That period is why many explanations still present chaining as the modern approach and probing to the next free slot as the old one.

Then the hardware changed the trade. Following a pointer to a node somewhere else in the heap is a cache miss, and a cache miss became expensive compared to the few comparisons a probe does inside one contiguous array. Google presented Swiss tables in 2017 and open-sourced them in Abseil, and the design brought open addressing back to the fast end: Rust's HashMap switched to it in 2019, and Go's map in Go 1.24, in 2025.

Open addressing is now what the fastest general-purpose tables use. Python's dict, Rust's HashMap and Go's map all do, the last two with Swiss tables, an open-addressing design that keeps 7 bits of each slot's hash in a separate control byte, so a probe checks a whole group of slots with a few instructions before comparing any key.

Chaining remains in Java's HashMap and C++'s std::unordered_map, and C++ can't easily leave it. The C++ standard promises that a pointer to an element stays valid when the table grows, which is easy when every entry is its own node and hard when entries move around inside an array.

The chain doesn't have to be a linked list either. Java's HashMap turns a bucket into a red-black tree (see Balanced trees) once it holds 8 entries and the table has at least 64 buckets, so a bucket that many keys land on costs O(log n) to search instead of O(n), and it goes back to a list when the bucket shrinks to 6. Go's map before 1.24 mixed the two strategies: each bucket was a small array of 8 entries, and a full bucket chained to an overflow bucket.

A bucket can even hold a second, small hash table. Two-level hashing (Fredman, Komlós and Szemerédi, 1984) gives each bucket its own table, sized and given its own hash function so that nothing collides inside it, which makes every lookup two hash computations in the worst case. It only works for a set of keys fixed in advance, so general-purpose maps don't use it.

Load factor and rehashing

The load factor α = n/m, where n is the number of stored entries and m is the number of buckets. As α rises, performance degrades: chains grow longer (chaining) or clustering worsens (open addressing). Both erode the O(1) average toward O(n).

With a good hash function, α is also roughly the chance that a new key collides. A table with 10 slots and 2 entries has α = 0.2: the new key is equally likely to land in any of the 10 slots, 2 of them are taken, so it hits an occupied one 20% of the time. At α = 0.75 it's three times out of four. Under chaining two entries can share a bucket, which leaves fewer buckets occupied, so there the chance is at most α.

When α exceeds a threshold, typically 0.75, the table must grow. This is called rehashing.

The threshold trades memory for collisions. A low one keeps collisions rare but leaves most of the array empty; a high one uses the array better but makes chains and probe sequences longer. Real implementations settle near 0.7: Java's HashMap grows at 0.75, Python's dict at 2/3 and Go's Swiss-table map at 7/8. Growing is expensive because the slot is hash % m and m just changed, so every entry has to be placed again, not just copied over:

  1. Allocate a new, larger array (typically 2× the bucket count)
  2. Re-hash every existing entry and insert it into the new table
  3. Free the old table
C
/* Conceptual rehash: double the table, re-insert every entry */void rehash(struct HashTable *old_ht, struct HashTable *new_ht) {    ht_init(new_ht);  /* new_ht->buckets has 2x the slots */    for (int i = 0; i < OLD_SIZE; i++) {        struct Entry *curr = old_ht->buckets[i];        while (curr) {            ht_insert(new_ht, curr->key, curr->value);            curr = curr->next;        }    }}
Cost of each insert, rehashing at load factor 0.75
  • Insert
  • Insert that rehashes
  • Average cost per insert
01325Insert #1: 1 writeInsert #2: 1 writeInsert #3: 1 writeInsert #4: copies 3 elements, then writesInsert #5: 1 writeInsert #6: 1 writeInsert #7: copies 6 elements, then writesInsert #8: 1 writeInsert #9: 1 writeInsert #10: 1 writeInsert #11: 1 writeInsert #12: 1 writeInsert #13: copies 12 elements, then writesInsert #14: 1 writeInsert #15: 1 writeInsert #16: 1 writeInsert #17: 1 writeInsert #18: 1 writeInsert #19: 1 writeInsert #20: 1 writeInsert #21: 1 writeInsert #22: 1 writeInsert #23: 1 writeInsert #24: 1 writeInsert #25: copies 24 elements, then writesInsert #26: 1 writeInsert #27: 1 writeInsert #28: 1 writeInsert #29: 1 writeInsert #30: 1 writeInsert #31: 1 writeInsert #32: 1 writeInsert #33: 1 writeInsert #34: 1 writeInsert #35: 1 writeInsert #36: 1 writeInsert #37: 1 writeInsert #38: 1 writeInsert #39: 1 writeInsert #40: 1 writeInsert #41: 1 writeInsert #42: 1 writeInsert #43: 1 writeInsert #44: 1 writeInsert #45: 1 writeInsert #46: 1 writeInsert #47: 1 writeInsert #48: 1 write≈ 1.948 inserts, in orderoperations

Common operations and their costs

OperationAverageWorst caseWhy
insertHash then place; worst if all keys collide
lookupHash then scan chain; worst if all keys collide
deleteHash then unlink; worst if all keys collide
rehash—O(n)Re-insert all n entries; amortized O(1) per insert
Iterate all entriesO(n + m)O(n + m)Must scan all m buckets even if most are empty

An attacker can trigger the worst case on purpose: if they know the hash function, they can craft keys that all hash to the same slot and turn every lookup into a linear scan. This is called a hash flooding attack and has been used against web servers. Modern hash table implementations defend against it with randomized seeds, a per-process or per-table salt added to the hash computation, so the attacker cannot predict which keys will collide. Rust's HashMap uses SipHash by default for this reason.

Hash tables in the real world

Language runtimes. Python dictionaries and JavaScript objects are hash tables. Every expression like obj["username"] or obj.username goes through a hash function at runtime. The global variables of every Python module live in a dict: the variable names are the keys, and their values are the dict values. Local variables inside a function are the exception: CPython keeps them in a fixed-size array and builds a dict only when you call locals(). V8 (the JavaScript engine) uses a combination of inline object shape caches and hash tables depending on the object's history and the number of properties it holds.

Database hash indexes. Relational databases offer hash indexes alongside the more common B-tree index. In PostgreSQL: CREATE INDEX ON users USING hash (email). A hash index is significantly faster for equality lookups (WHERE email = 'alice@example.com') because it computes the index position directly. It is completely useless for range queries (WHERE created_at BETWEEN ... AND ...) because hashing destroys all ordering information. Most databases default to B-tree precisely because range queries are common; hash indexes are a specialized optimization for pure equality workloads.

Caches and content deduplication. Content-addressable storage systems use cryptographic hashes as keys. Git stores every file and commit object under its SHA-1 hash. Two files with identical content produce the same hash, so checking "have I already stored this content?" is a hash table lookup, O(1) no matter how many objects are stored. Backup deduplication software works the same way: hash each block of data, look it up in a hash table of already-seen blocks, skip if found.

Compiler symbol tables. Every compiler maintains a symbol table: a mapping from identifier names (strings) to their declarations, types, and memory addresses. During compilation, every variable reference (x = y + 1) involves two hash table lookups, one for x and one for y. Compilers pick a hash table over a sorted structure because identifier names are not naturally sorted, the load is dominated by repeated lookups of a stable key set, and the hash table's O(1) average dominates on this workload.

Set data structures. A mathematical set (a collection with no duplicates, where membership testing is the main operation) is implemented as a hash table that discards values and stores only keys. Python's set, Java's HashSet, and C++'s unordered_set are hash tables with empty values. The expression if x in seen: in Python is a hash table lookup, not a linear scan.

Pseudo-random number generation. A hash function that distributes its outputs uniformly across a range is, structurally, a pseudo-random number generator. Feed it a counter and you get a deterministic sequence that looks random:

C
/* Integer finalizer — maps any uint32 to a uniform-looking uint32 */uint32_t hash_u32(uint32_t x) {    x = ((x >> 16) ^ x) * 0x45d9f3b;    x = ((x >> 16) ^ x) * 0x45d9f3b;    x =  (x >> 16) ^ x;    return x;}/* Stateless: the nth value, without computing the ones before it */float random_at(uint32_t seed, uint32_t n) {    return hash_u32(seed ^ n) / (float)0xFFFFFFFFu;}

A sequential PRNG holds state and must be advanced one step at a time. A hash-based generator is stateless and parallelizable, so you can jump directly to any index in the sequence: random_at(seed, 1000000) costs exactly as much as random_at(seed, 0).

Procedural generation depends on this. To assign a random elevation to terrain chunk (x, y), compute hash(seed ^ x ^ (y * large_prime)): there is no shared state and no ordering constraint, and the same seed gives identical results across machines and threads. The same principle underlies Perlin and Simplex noise functions, which hash grid-point coordinates to produce smooth random fields. Shader code, game world generation and deterministic simulation use the pattern because it gives indexed, parallel access to any point in a random sequence without any coordination between threads.

When hash tables fall short

No ordering. Hash tables store entries in essentially random bucket positions, because the hash function makes no attempt to preserve any relationship between keys. You cannot iterate all keys in sorted order, and you cannot answer range queries like "all keys between 'apple' and 'banana'". For ordered access, use a balanced BST (std::map in C++, TreeMap in Java), which gives O(log n) operations with full range-query support.

Poor cache performance under chaining. Chaining's linked list nodes are allocated individually on the heap, scattered through memory. Under high load, traversing a long chain causes a cache miss on every step. Open addressing avoids this with contiguous storage, but it introduces clustering and tombstone accumulation over time.

Worst-case O(n) under adversarial input. Without a randomized seed, a known hash function can be exploited to produce pathological inputs that degrade every operation to O(n). Hash flooding attacks against web frameworks have been documented. In security-sensitive contexts, always use a hash function with a random salt.

Memory overhead from empty buckets. A hash table always maintains excess capacity to keep the load factor low. A table with 100 entries at α = 0.5 allocates 200 buckets, half of them empty. For very small key sets, a sorted array with binary search may use less total memory and be faster in practice due to cache behavior.

Rehashing pauses. Each rehash is an O(n) synchronous operation. In most implementations it happens at insertion time, without warning. For latency-sensitive systems such as real-time audio processing or high-frequency trading, an unpredictable O(n) pause is unacceptable. Redis addresses this with incremental rehashing: it keeps two tables during a resize and migrates a few entries on each operation, which spreads the cost across many operations.

Summary

Hash tables are the fastest general-purpose lookup structure for arbitrary key types:

  • Insert, lookup and delete are O(1) on average, because a hash function maps each key to an array index
  • Collisions are inevitable, and the table is built to handle them, by chaining (a linked list per bucket) or by open addressing (linear probing into adjacent slots)
  • The load factor is α = n/m; keep it below 0.75, and crossing the threshold triggers rehashing
  • Rehashing is amortized O(1): the O(n) cost is paid once every n insertions, the same structure as dynamic array doubling
  • Hash tables give up ordering and keep no relationship between keys; use a tree-based map when sorted access or range queries matter
  • Python dict, JavaScript objects, database row caches, compiler variable environments and deduplication systems are all hash tables