← The Ledger
Vol. I, No. 24 · Hash Structures

The Hash Table

An array indexed by a function of the key, with a policy for when two keys want the same slot.

Written by Khushal Agrawal

loading…

Hashing To A Bucket

A hash table stores key-value pairs in an array of m slots and computes where each key belongs instead of searching for it. A hash function turns the key into a machine word, and the low bits of that word select a slot. With m a power of two, the reduction is a mask rather than a division.

uint64_t h = hash(key);          // "cat" -> 0x7c3e91a5
size_t   i = h & (m - 1);        // m = 8: low three bits -> slot 5

Two distinct keys can land in the same slot, and with more keys than slots they must. Everything else in this chapter is a policy for that collision: where the second key goes, how a lookup finds it, and what happens when the table fills.

Hash Functions

The table's bounds assume the hash spreads keys uniformly over the slots it actually uses. Masking keeps only the low bits, so a hash whose low bits are weak — string length, a pointer aligned to 16 bytes, a sequential ID multiplied by a power of two — sends many keys to a few slots. Multiplicative hashing mixes high bits down before the table takes its share.

// Fibonacci hashing: multiply by 2^64 / phi, keep the top bits
size_t slot(uint64_t h, int bits) {
    return (h * 11400714819323198485ull) >> (64 - bits);
}

Production tables use full-avalanche functions such as SipHash, wyhash, or xxHash, where flipping any input bit flips each output bit with probability one half. The hash must also stay fixed for the life of the table, so a key mutated after insertion becomes unreachable.

Separate Chaining

Separate chaining makes each slot the head of a linked list. Insertion pushes a node onto the list for its slot; lookup hashes once, then walks that one list comparing keys.

node *get(table *t, key_t k) {
    node *n = t->bucket[hash(k) & t->mask];
    for (; n; n = n->next)
        if (eq(n->key, k)) return n;
    return NULL;
}

Deletion unlinks a node and leaves every other entry where it was, which is the main reason chaining survives in kernels and databases. The cost is a pointer and an allocation per entry, and a cache miss per chain hop, since the nodes live wherever the allocator put them.

Load Factor

The load factor α = n / m is the average chain length. Under uniform hashing a successful search examines about 1 + α/2 nodes and an unsuccessful one examines about α, so the expected cost of every operation is O(1 + α). Holding α below a constant keeps the table at expected constant time.

That bound is expected, not worst-case. Nothing stops all n keys from hashing to one slot, at which point a lookup is a linear scan of an O(n) list. Chained tables tolerate α above 1 — Java's HashMap resizes at 0.75 and Redis at 1 — because a longer chain degrades gradually rather than failing. Open-addressed tables, below, cannot exceed 1 at all.

Linear Probing

Open addressing stores entries in the slot array itself. When the home slot is taken, the key goes to the next slot in a fixed probe sequence; linear probing uses the very next slot, wrapping at the end.

size_t i = hash(k) & mask;
while (slot[i].used) {
    if (eq(slot[i].key, k)) return &slot[i];
    i = (i + 1) & mask;
}
return NULL;                    // an empty slot ends the search

No pointers and no allocation per entry: a probe sequence reads adjacent memory, often within one cache line. The stop condition is the subtle part. A lookup may only conclude absence at an empty slot, because any occupied slot it passes could be part of the run its key was pushed into.

Primary Clustering

Linear probing builds runs. A key that hashes anywhere inside a run of occupied slots lands at its end and extends it, so long runs grow faster than short ones and adjacent runs merge. Knuth's 1963 analysis gives the expected probe counts under uniform hashing.

successful    ≈ 1/2 (1 + 1/(1 - α))
unsuccessful  ≈ 1/2 (1 + 1/(1 - α)^2)

α = 0.50   →  1.5 hit,   2.5 miss
α = 0.75   →  2.5 hit,   8.5 miss
α = 0.90   →  5.5 hit,  50.5 miss

The quadratic term in the miss cost is why linear-probing tables cap α near 0.7. Quadratic probing and double hashing scatter the sequence to avoid clustering, but give up the sequential access that makes linear probing fast on real hardware.

Deletion And Tombstones

Deleting from an open-addressed table cannot simply empty the slot. If emu sits between cat and fox in one run and is removed, a later lookup for fox starts at its home slot, hits the hole, and reports fox absent while it is still stored one slot further on.

enum { EMPTY, FULL, TOMBSTONE };

// lookup: a tombstone is skipped, not a stop
while (slot[i].state != EMPTY) { ... }
// insert: the first tombstone seen may be reused

The usual fix marks the slot with a tombstone. Lookups probe past it and inserts may reclaim it. Tombstones still lengthen probe sequences and count toward the resize threshold, so a delete-heavy workload eventually needs a rehash that clears them, even at constant size.

Backward-Shift Deletion

Linear probing allows deletion with no tombstones. After emptying slot i, scan forward through the run and move each entry back into the hole if the hole lies on that entry's probe path — between its home slot and its current slot, cyclically.

void erase(size_t i) {
    for (size_t j = i;;) {
        j = (j + 1) & mask;
        if (!slot[j].used) break;
        size_t h = hash(slot[j].key) & mask;
        bool home_in_gap = (i <= j) ? (i < h && h <= j)
                                    : (i < h || h <= j);
        if (!home_in_gap) { slot[i] = slot[j]; i = j; }
    }
    slot[i].used = false;
}

This is Knuth's Algorithm R. It restores exactly the table that insertion without the deleted key would have built, at the cost of rehashing each entry in the rest of the run.

Resizing And Rehashing

When α crosses its threshold the table allocates an array twice the size and reinserts every entry. Positions cannot be copied, because the slot depends on m: going from mask 3 to mask 7 exposes one more hash bit, so each key either stays at index i or moves to i + m.

void grow(table *t) {
    table old = *t;
    init(t, 2 * old.cap);
    for (size_t i = 0; i < old.cap; i++)
        if (old.slot[i].used) insert_fresh(t, old.slot[i]);
    free(old.slot);
}

One resize costs O(n), but doubling means it happens after n cheap inserts, so insertion is O(1) amortized — the same argument that pays for a growing deque. The latency of the single expensive insert remains.

Incremental Rehashing

A server that cannot stall for an O(n) copy spreads the resize over later operations. Redis keeps two tables, ht[0] and ht[1], and an index rehashidx marking how far migration has progressed. Every lookup, insert, and delete moves one bucket from the old table to the new one before doing its own work.

if (rehashidx != -1) {               // a resize is in progress
    move_bucket(ht[0], rehashidx, ht[1]);
    if (++rehashidx == ht[0].size) finish_rehash();
}
// lookups check ht[0], then ht[1]; inserts go only to ht[1]

The worst-case cost per operation becomes one bucket's chain plus the operation itself. The price is up to twice the memory during migration and two probes on a lookup miss. Redis also spends about a millisecond per cron tick advancing the migration when the server is idle.

Robin Hood Hashing

Celis, Larson, and Munro's Robin Hood hashing keeps linear probing but changes who gets a contested slot. Each entry's probe distance is how far it sits from its home slot. During insertion, the incoming entry takes any slot whose occupant is closer to home than the newcomer is, and the displaced entry continues probing.

for (size_t d = 0;; d++, i = (i + 1) & mask) {
    if (!slot[i].used) { slot[i] = e; return; }
    size_t rd = (i - home(slot[i])) & mask;
    if (rd < d) { swap(e, slot[i]); d = rd; }   // the poorer entry stays
}

Mean probe length is unchanged, but its variance collapses, and a lookup can stop as soon as it reaches an entry closer to home than itself. Rust's standard HashMap used Robin Hood hashing with backward-shift deletion until version 1.36 in 2019.

Swiss Tables And SIMD Probing

Abseil's Swiss table splits the hash in two. The high 57 bits, H1, choose a group of 16 slots; the low 7 bits, H2, are stored in a separate one-byte control array, one byte per slot, with reserved values for empty and deleted.

__m128i ctrl  = _mm_loadu_si128(group);          // 16 control bytes
__m128i match = _mm_cmpeq_epi8(ctrl, _mm_set1_epi8(h2));
uint32_t bits = _mm_movemask_epi8(match);         // one bit per candidate
for (; bits; bits &= bits - 1)
    if (eq(slots[ctz(bits)].key, k)) return ...;

One SSE2 compare tests 16 slots, and a full key comparison happens only where the 7-bit tag matches, a false-positive rate of 1 in 128 per occupied slot. The table runs at a load factor up to 7/8. Rust's hashbrown, the standard HashMap since 1.36, and Go's maps since 1.24 use this design.

Hash Flooding

Expected O(1) assumes the keys are not chosen against the hash function. An attacker who knows the function can submit n keys that all land in one bucket, making the n inserts cost Θ(n²) in total. Crosby and Wallach demonstrated the attack in 2003; in 2011 Klink and Wälde showed that one crafted POST request full of colliding parameter names could keep a CPU core busy for minutes on PHP, Java, Python, and Ruby web stacks.

The defence is a keyed hash with a secret per-process seed, so collisions cannot be computed offline. SipHash was designed for this, and Python adopted it in 3.4 (PEP 456). Java took the other route in JDK 8: a HashMap bucket with eight or more entries converts to a red-black tree, capping the damage at O(log n).

Engineering Trade-offs

A hash table gives expected O(1) lookup, insert, and delete, and amortized O(1) insertion including growth. An open-addressed table stores entries inline with a few bytes of metadata each, and a lookup usually costs one or two cache misses. No other general-purpose map is faster for exact-match access on a key set that fits in memory.

It gives up order. There is no successor query, no range scan, and no prefix search; a skip list or a trie provides those. Guarantees are probabilistic and depend on the hash, resizes add latency spikes unless incremental, and iteration order is arbitrary. A persistent variant needs a different layout — the hash-array mapped trie — because copying a flat array per update costs O(n).

Applications

CPython resolves attribute access, global lookups, and keyword arguments through dict. Since 3.6, Objects/dictobject.c stores a sparse array of small integer indices alongside a dense, insertion-ordered entry array, probing with i = (i*5 + perturb + 1) & mask so every hash bit eventually influences the sequence. The Linux kernel's dentry cache maps a (parent directory, name) pair to its struct dentry through a chained table that path lookup walks under RCU without taking locks.

PostgreSQL's hash join, in src/backend/executor/nodeHash.c, builds a chained table from the smaller input and probes it with each row of the larger; when the table exceeds work_mem it splits into batches spilled to disk. Memcached's assoc.c expands its item table with a background thread that migrates buckets incrementally while requests continue.

Summary

A hash table maps a key to a slot by hashing it and masking the result, then resolves collisions either by chaining entries in per-slot lists or by probing for another slot in the array. Holding the load factor below a constant keeps lookup, insert, and delete at expected O(1), and doubling on overflow keeps insertion amortized O(1).

The costs are a worst case of O(n) under bad or adversarial hashing, a latency spike at each resize unless it is spread incrementally, deletion that needs tombstones or back-shifting under open addressing, and no ordering of any kind. Robin Hood displacement and Swiss-table control bytes do not change those bounds; they reduce the probe-length variance and the number of full key comparisons.

The Hash Table: An array indexed by a function of the key, with a policy for when two keys want the same slot
The Hash Table — An array indexed by a function of the key, with a policy for when two keys want the same slot.

Sources & further reading

Every claim in this chapter traces to a primary source. Peer-reviewed papers are linked by DOI.

Primary sources

  1. Knuth, D. E. (1998). The Art of Computer Programming, Vol. 3: Sorting and Searching (2nd ed.), §6.4. Addison-Wesley. www-cs-faculty.stanford.edu/~knuth/taocp.html
  2. Celis, P., Larson, P.-Å., & Munro, J. I. (1985). Robin Hood hashing. 26th Annual Symposium on Foundations of Computer Science, 281–288. doi.org/10.1109/SFCS.1985.48
  3. Crosby, S. A., & Wallach, D. S. (2003). Denial of service via algorithmic complexity attacks. 12th USENIX Security Symposium. www.usenix.org/conference/12th-usenix-security-symposium/denial-service-algorithmic-complexity-attacks
  4. Klink, A., & Wälde, J. (2011). Efficient denial of service attacks on web application platforms. 28th Chaos Communication Congress. fahrplan.events.ccc.de/congress/2011/Fahrplan/events/4680.en.html
  5. Aumasson, J.-P., & Bernstein, D. J. (2012). SipHash: a fast short-input PRF. INDOCRYPT 2012, LNCS 7668, 489–508. doi.org/10.1007/978-3-642-34931-7_28
  6. Kulukundis, M. (2017). Designing a fast, efficient, cache-friendly hash table, step by step. CppCon 2017. abseil.io/about/design/swisstables

Applications and implementations

  1. Python Software Foundation. Objects/dictobject.c — compact dict and perturbed probing. github.com/python/cpython/blob/main/Objects/dictobject.c
  2. Heimes, C. (2013). PEP 456 — Secure and interchangeable hash algorithm. peps.python.org/pep-0456/
  3. Redis. src/dict.c — two-table incremental rehashing. github.com/redis/redis/blob/unstable/src/dict.c
  4. The Linux Kernel. fs/dcache.c — dentry hash table and RCU path lookup. github.com/torvalds/linux/blob/master/fs/dcache.c
  5. PostgreSQL Global Development Group. src/backend/executor/nodeHash.c. github.com/postgres/postgres/blob/master/src/backend/executor/nodeHash.c
  6. Memcached. assoc.c — incremental table expansion thread. github.com/memcached/memcached/blob/master/assoc.c
  7. OpenJDK. JEP 180: Handle frequent HashMap collisions with balanced trees. openjdk.org/jeps/180
  8. The Go Authors (2025). Faster Go maps with Swiss Tables. go.dev/blog/swisstable
  9. rust-lang. hashbrown — a Rust port of Swiss tables. github.com/rust-lang/hashbrown

Enjoyed this chapter? Support The Ledger.