data structureshashing

hash table

hash the key to a bucket number, so a lookup is one jump instead of a search.

report a mistake
.md

hash the key to a number. that number mod the bucket count says where the key lives, and keys that land in the same bucket share it.

get
O(1) average. O(n) if every key collides
put
O(1) average, amortized over the resizes
remove
O(1) average
resize
O(n) every key placed again, once per doubling
min, max
O(n) no order to use, so check every key
reach for it
  • counting things
  • caches and memoizing
  • sets of things already seen
  • lookups by id or name
  • group-by and joins
on this page
  1. the idea
  2. collisions
  3. the easy part: chaining
  4. the operations
  5. try it
  6. pseudocode
  7. put and resize, up close
  8. linear probing
  9. complexity
  10. implementations
  11. pitfalls
  12. variants
  13. practice
  14. how real libraries do it
  15. sources

an array finds item 5 in one step, because 5 says where it is: the start of the array plus 5 slots. a hash table gives any key that kind of address. it hashes the key to a big number, and that number mod the bucket count picks one bucket. a lookup goes straight to that bucket instead of searching.

the idea

utf-8 bytes
63 61 74
fnv-1a
0x06745c07 = 108289031
mod 8
bucket 7
nextcat
0
1
2
3
4
5
6
7

cat will land in bucket 7.

type a key, like cat, and the figure shows the key's utf-8 bytes, its 32-bit fnv-1a hash in hex and in decimal, and the hash mod 8: a bucket number from 0 to 7. drop it in and the key lands in that bucket, in a row of 8. a key that lands in a bucket that already holds one is a collision, and the bucket flashes amber: cat and bee both land in bucket 7.

type a key and watch it turn into an address: its bytes, the hash of those bytes, then the hash mod 8, a bucket from 0 to 7. the same key always lands in the same bucket, because the hash depends only on the bytes. try cat, then bee: two keys, one bucket.

the hash here is fnv-1a, 32 bits: start from a fixed number, then for each byte, xor it in and multiply by a fixed prime.1 every language on this page uses it, so a key lands in the same bucket in each one, and in the figures.

collisions

9 keys in 8 buckets means two keys share a bucket: there aren’t enough buckets to go around. it happens long before that. put 4 random keys in 8 buckets, and the chance that at least two share one is 1−8⋅7⋅6⋅5841 - \frac{8 \cdot 7 \cdot 6 \cdot 5}{8^4}, about 59%. it’s the birthday problem: a collision is the normal case, not a rare one.

so a hash table needs a plan for two keys in one bucket. there are two common ones:

the easy part: chaining

each bucket is a short list of (key, value) pairs. put finds the bucket and walks its list: if the key is there, it changes the value, and if not, it adds the pair at the end. get walks the same list comparing keys. remove takes the pair out.

walking a list sounds slow, but the lists stay short. with n keys in m buckets, a list holds n / m keys on average. that ratio is the load factor. keep it under a constant, and the average walk is a constant too: this table doubles its buckets before the load passes 0.75.

the operations

8 buckets, 0 keys: load 0.00

0
1
2
3
4
5
6
7

put a few keys in: cat and bee share a bucket, and the seventh key makes the table grow.

keys compared
0
pseudocode
index(key, n):  # fnv-1a, 32-bit, then mod n  h = 2166136261  for b in utf8_bytes(key):    h = ((h ^ b) * 16777619) % 2**32  return h % n put(t, key, value):  chain = t.buckets[index(key, len(t.buckets))]  for entry in chain:    if entry.key == key:      entry.value = value  # an update: the size and the buckets stay      return  if (t.size + 1) / len(t.buckets) > 0.75:    resize(t, 2 * len(t.buckets))    chain = t.buckets[index(key, len(t.buckets))]  chain.append((key, value))  t.size += 1 get(t, key):  for entry in t.buckets[index(key, len(t.buckets))]:    if entry.key == key: return entry.value  return none remove(t, key):  chain = t.buckets[index(key, len(t.buckets))]  for i in range(len(chain)):    if chain[i].key == key:      del chain[i]      t.size -= 1      return true  return false resize(t, n):  # the hash stays, the bucket count changes, so keys move  old = t.buckets  t.buckets = [[] for _ in range(n)]  for chain in old:    for entry in chain:      t.buckets[index(entry.key, n)].append(entry)

an interactive hash table with 8 buckets, each a chain of keys. type a key and put, get or remove it: the key's hash and bucket show first, then the walk down that bucket's chain, one key compared at a time, with the pseudocode line highlighted and a count of keys compared. cat and bee share bucket 7. after six keys, a seventh, yak, would push the load past 0.75, so the table doubles to 16 buckets first, and each key either stays in its bucket or moves 8 buckets over.

put, get or remove a key. its hash and bucket show first, then the walk down the chain, with the pseudocode following along. next key fills in the demo keys in order: cat, dog, owl, then bee, which joins cat in bucket 7. after six keys, the seventh, yak, would make 7 keys in 8 buckets, a load of 0.875, so the table doubles to 16 first and every key goes in again.

try it

bee hashes to 0x51ae487f. which of 8 buckets does it go in?

bee → 0x51ae487f

pick one.

0 / 0 right

a practice exercise. given a key and its 32-bit hash in hex, pick which of 8 buckets it goes in: the hash mod 8, which the last hex digit decides. then the table doubles to 16, and you pick where the same key goes: the same bucket, or 8 further on, depending on one more bit of the hash.

the last hex digit of the hash is its last 4 bits, and mod 8 keeps the last 3. work out the bucket, then pick it.

pseudocode

pseudocode
index(key, n):  # fnv-1a, 32-bit, then mod n
  h = 2166136261
  for b in utf8_bytes(key):
    h = ((h ^ b) * 16777619) % 2**32
  return h % n

put(t, key, value):
  chain = t.buckets[index(key, len(t.buckets))]
  for entry in chain:
    if entry.key == key:
      entry.value = value  # an update: the size and the buckets stay
      return
  if (t.size + 1) / len(t.buckets) > 0.75:
    resize(t, 2 * len(t.buckets))
    chain = t.buckets[index(key, len(t.buckets))]
  chain.append((key, value))
  t.size += 1

get(t, key):
  for entry in t.buckets[index(key, len(t.buckets))]:
    if entry.key == key: return entry.value
  return none

remove(t, key):
  chain = t.buckets[index(key, len(t.buckets))]
  for i in range(len(chain)):
    if chain[i].key == key:
      del chain[i]
      t.size -= 1
      return true
  return false

resize(t, n):  # the hash stays, the bucket count changes, so keys move
  old = t.buckets
  t.buckets = [[] for _ in range(n)]
  for chain in old:
    for entry in chain:
      t.buckets[index(entry.key, n)].append(entry)

index is the hash, then the mod. t.size is the number of keys. put checks the load before it adds a key, and counts the key it’s about to add.

put and resize, up close

linear probing

open addressing keeps every key in one array of slots, with no lists. linear probing is its simplest form: a key goes in its home slot, h % capacity, and if that’s taken, in the next one, and the next, wrapping at the end. a lookup walks the same way from home, until it finds the key or an empty slot. an empty slot ends the search: if the key were in the table, its put would have stopped there.

8 slots, 0 keys, 0 used: load 0.00

0
1
2
3
4
5
6
7

put a few keys in: cat and bee share a bucket, and the seventh key makes the table grow.

slots looked at
0
pseudocode
find(t, key):  # the slot holding key, or none  i = index(key, t.cap)  while t.slots[i] is not empty:    if t.slots[i] is not a tombstone and t.slots[i].key == key: return i    i = (i + 1) % t.cap  return none landing(t, key):  # where a new key goes: the first tombstone or empty slot  i = index(key, t.cap)  while t.slots[i] holds a key:    i = (i + 1) % t.cap  return i put(t, key, value):  i = find(t, key)  if i is not none:    t.slots[i].value = value    return  i = landing(t, key)  if t.slots[i] is empty:  # reusing a tombstone takes no new room    if (t.used + 1) / t.cap > 0.75:      resize(t, 2 * t.cap)      i = landing(t, key)    t.used += 1  # used counts tombstones too  t.slots[i] = (key, value)  t.size += 1 get(t, key):  i = find(t, key)  return none if i is none else t.slots[i].value remove(t, key):  i = find(t, key)  if i is none: return false  t.slots[i] = tombstone  # emptying it would cut off keys that probed past it  t.size -= 1  return true resize(t, n):  # live keys only: the tombstones are dropped  old = t.slots  t.slots, t.cap, t.size, t.used = [empty] * n, n, 0, 0  for slot in old:    if slot holds a key: put(t, slot.key, slot.value)

the same playground with linear probing: one row of 8 slots and no chains. a put starts at the key's home slot, in cyan, and walks right one slot at a time, in amber, wrapping at the end, until it finds the key or a free slot. with the six demo keys, bee's home is 7 like cat's, so it wraps to slot 0, and cow walks from its home, 0, to slot 2. a remove leaves a dashed tombstone that lookups walk past. a checkbox makes remove empty the slot instead, and then a lookup for cow stops at the empty slot 0 and misses, though cow is still in slot 2.

the home slot is cyan, each step of a walk amber, and the counter tracks slots looked at. put the six demo keys: bee’s home is 7, like cat’s, so it walks on and wraps to slot 0. cow’s home is 0, so it walks to slot 2.

removing is the hard part. empty bee’s slot and cow is lost: a lookup for cow starts at slot 0, finds it empty and stops, though cow is still sitting in slot 2. tick the checkbox to remove by emptying, then remove bee and get cow.

the fix is a tombstone: a removed key leaves a marker that says something was here. a lookup walks past a tombstone, and a put can reuse it. untick the box and try again: the get for cow walks 0, 1, 2 and finds it.

tombstones cost something too. they aren’t keys, but a walk still has to step over them, so they count toward the load: the figure’s used count. a resize drops them. python’s dict leaves tombstones (it calls them dummy slots),3 while swift’s Dictionary avoids them: after a remove, it moves later keys in the same run back into the hole4

pseudocode
find(t, key):  # the slot holding key, or none
  i = index(key, t.cap)
  while t.slots[i] is not empty:
    if t.slots[i] is not a tombstone and t.slots[i].key == key: return i
    i = (i + 1) % t.cap
  return none

landing(t, key):  # where a new key goes: the first tombstone or empty slot
  i = index(key, t.cap)
  while t.slots[i] holds a key:
    i = (i + 1) % t.cap
  return i

put(t, key, value):
  i = find(t, key)
  if i is not none:
    t.slots[i].value = value
    return
  i = landing(t, key)
  if t.slots[i] is empty:  # reusing a tombstone takes no new room
    if (t.used + 1) / t.cap > 0.75:
      resize(t, 2 * t.cap)
      i = landing(t, key)
    t.used += 1  # used counts tombstones too
  t.slots[i] = (key, value)
  t.size += 1

get(t, key):
  i = find(t, key)
  return none if i is none else t.slots[i].value

remove(t, key):
  i = find(t, key)
  if i is none: return false
  t.slots[i] = tombstone  # emptying it would cut off keys that probed past it
  t.size -= 1
  return true

resize(t, n):  # live keys only: the tombstones are dropped
  old = t.slots
  t.slots, t.cap, t.size, t.used = [empty] * n, n, 0, 0
  for slot in old:
    if slot holds a key: put(t, slot.key, slot.value)

the tested typescript behind the figure:

site/src/visuals/hash-table/linear-probing.ts
import { fnv1a } from './hash-table';

/**
 * Open addressing with linear probing: every key lives in one array, and a collision walks on to the
 * next slot. A remove leaves a tombstone, so the keys that probed past it can still be found.
 */
type Entry = { key: string; value: number };
const TOMBSTONE = 'tombstone';
type Slot = Entry | typeof TOMBSTONE | null;

export class ProbingTable {
  #slots: Slot[] = new Array<Slot>(8).fill(null);
  #size = 0; // live keys
  #used = 0; // live keys plus tombstones: both stop a probe, so both count toward the load factor

  get size(): number {
    return this.#size;
  }

  get capacity(): number {
    return this.#slots.length;
  }

  put(key: string, value: number): void {
    const at = this.#find(key);
    if (at !== null) {
      (this.#slots[at] as Entry).value = value;
      return;
    }
    let i = this.#landing(key);
    if (this.#slots[i] === null) {
      // a fresh slot: grow first if it would push the load factor past 0.75. reusing a tombstone takes no
      // new room, so it never resizes
      if ((this.#used + 1) * 4 > this.#slots.length * 3) {
        this.#resize(this.#slots.length * 2);
        i = this.#landing(key);
      }
      this.#used += 1;
    }
    this.#slots[i] = { key, value };
    this.#size += 1;
  }

  get(key: string): number | undefined {
    const at = this.#find(key);
    return at === null ? undefined : (this.#slots[at] as Entry).value;
  }

  remove(key: string): boolean {
    const at = this.#find(key);
    if (at === null) return false;
    this.#slots[at] = TOMBSTONE; // emptying it would cut off the keys that probed past it
    this.#size -= 1;
    return true;
  }

  /** Each slot: its key, 'tombstone', or null. */
  layout(): (string | typeof TOMBSTONE | null)[] {
    return this.#slots.map((s) => (s === null || s === TOMBSTONE ? s : s.key));
  }

  /** The slot holding key, walking from its home slot until an empty one. */
  #find(key: string): number | null {
    let i = fnv1a(key) % this.#slots.length;
    for (let steps = 0; steps < this.#slots.length && this.#slots[i] !== null; steps++) {
      const s = this.#slots[i];
      if (s !== TOMBSTONE && s!.key === key) return i;
      i = (i + 1) % this.#slots.length;
    }
    return null;
  }

  /** Where a new key goes: the first tombstone or empty slot on its walk from home. */
  #landing(key: string): number {
    let i = fnv1a(key) % this.#slots.length;
    while (this.#slots[i] !== null && this.#slots[i] !== TOMBSTONE) i = (i + 1) % this.#slots.length;
    return i;
  }

  /** Live keys only: the tombstones are dropped. */
  #resize(n: number): void {
    const old = this.#slots;
    this.#slots = new Array<Slot>(n).fill(null);
    this.#size = 0;
    this.#used = 0;
    for (const s of old) if (s !== null && s !== TOMBSTONE) this.put(s.key, s.value);
  }
}

full slots clump into runs, and that’s the other cost. a key whose home is anywhere in a run walks to its end and makes the run longer, so long runs grow faster than short ones. that clustering is why probing slows down much faster than chaining as the table fills.

complexity

operationaverageworst
getO(1)O(n)
putO(1) amortizedO(n)
removeO(1)O(n)
resizeO(n)O(n)

the average assumes the hash spreads keys evenly over the buckets. the load stays at or under 0.75, so a chain holds less than one key on average.

the worst case is every key in one bucket: one chain of n keys, walked by every operation. a weak hash can do that by accident, and an attacker can do it on purpose (see the pitfalls). java’s HashMap caps the damage: adding to a bucket that already holds 8 keys turns it into a red-black tree, so a crowded bucket costs O(log n), as long as its keys have different hashes or can be ordered. that waits until the table has 64 buckets: a smaller table doubles instead2

put is O(1) amortized for the same reason a ring buffer’s push is: the resizes place 6, 12, 24, … keys, each twice the one before, so n puts cost less than 2n placements in all.

051000.250.50.751load factor: keys / bucketsresize
chaining, found
1.25
chaining, missing
0.50
probing, found
1.50
probing, missing
2.50

a line chart of the expected cost of one lookup as the load factor, keys per bucket, goes from 0 to 1. chaining, in cyan, rises slowly: 1 + α/2 keys compared when the key is there, α when it isn't. linear probing, in amber, stays low until about half full and then shoots up: at 0.75 a hit looks at 2.5 slots and a miss 8.5, and past 0.9 a miss looks at over 50. a dashed line marks 0.75, where this page's table resizes, and a slider moves a marker that reads off all four curves.

for chaining, the textbook counts are keys compared: about 1+α21 + \frac{\alpha}{2} when the key is there, and α\alpha when it isn’t, where α\alpha is the load factor. for linear probing, they’re slots looked at:5

hit≈12(1+11−α)miss≈12(1+1(1−α)2)\text{hit} \approx \frac{1}{2}\left(1 + \frac{1}{1 - \alpha}\right) \qquad \text{miss} \approx \frac{1}{2}\left(1 + \frac{1}{(1 - \alpha)^2}\right)

both assume the hash spreads keys evenly. at this page’s resize line, 0.75, chaining compares about 1.4 keys on a hit, while probing looks at 2.5 slots on a hit and 8.5 on a miss. past 0.9, a probing miss looks at over 50.

implementations

each tab is the real file from the repo, checked by its tests (go test, cargo test, vitest, make test, swift test, python -m unittest), including 2000 seeded puts, gets and removes checked against the language’s own map, or a plain array in c. all six hash with fnv-1a and resize at the same load, so a key sits in the same bucket in every one. a missing key is where they differ: go returns false as a second value, rust returns None, typescript undefined, c returns false, swift nil, and python None.

go/algos/hashtable/hashtable.go
// Package hashtable is a reference hash table with separate chaining: fnv-1a picks the bucket.
// O(1) average get, put, and remove; doubles past a 0.75 load factor.
package hashtable

import "slices"

// FNV1a hashes the key's bytes with 32-bit fnv-1a. go strings are utf-8 bytes already,
// so a key lands in the same bucket here as in the other languages.
func FNV1a(s string) uint32 {
	h := uint32(2166136261)
	for i := range len(s) { // by index: ranging over the string would give runes, not bytes
		h ^= uint32(s[i])
		h *= 16777619 // uint32 math wraps, which is the mod 2^32 the hash wants
	}
	return h
}

type entry struct {
	key   string
	value int
}

// Table maps string keys to ints. each bucket is a chain of entries.
// make one with New: the zero value has no buckets, so putting into it panics.
type Table struct {
	buckets [][]entry
	size    int
}

// New returns an empty table with 8 buckets.
func New() *Table {
	return &Table{buckets: make([][]entry, 8)}
}

// Len returns how many keys are in the table.
func (t *Table) Len() int {
	return t.size
}

// Buckets returns how many buckets there are.
func (t *Table) Buckets() int {
	return len(t.buckets)
}

// Put inserts the key, or updates its value if it's already here.
func (t *Table) Put(key string, value int) {
	b := t.bucket(key)
	for i := range t.buckets[b] {
		if t.buckets[b][i].key == key {
			t.buckets[b][i].value = value // an update: the size and the buckets stay
			return
		}
	}
	// a new key: grow first if it would push the load factor past 0.75
	if (t.size+1)*4 > len(t.buckets)*3 {
		t.resize(2 * len(t.buckets))
		b = t.bucket(key) // a new bucket count can move the key
	}
	t.buckets[b] = append(t.buckets[b], entry{key, value})
	t.size++
}

// Get returns the key's value, and false if the key isn't here.
func (t *Table) Get(key string) (int, bool) {
	for _, e := range t.buckets[t.bucket(key)] {
		if e.key == key {
			return e.value, true
		}
	}
	return 0, false
}

// Remove drops the key, and returns false if it wasn't here.
func (t *Table) Remove(key string) bool {
	b := t.bucket(key)
	for i, e := range t.buckets[b] {
		if e.key == key {
			t.buckets[b] = slices.Delete(t.buckets[b], i, i+1)
			t.size--
			return true
		}
	}
	return false
}

func (t *Table) bucket(key string) int {
	return int(FNV1a(key) % uint32(len(t.buckets)))
}

// resize places every key again: the hash stays, but the bucket count changes.
func (t *Table) resize(n int) {
	old := t.buckets
	t.buckets = make([][]entry, n)
	for _, chain := range old {
		for _, e := range chain {
			b := t.bucket(e.key)
			t.buckets[b] = append(t.buckets[b], e)
		}
	}
}
rust/algos/src/hash_table.rs
//! hash table with separate chaining: fnv-1a picks the bucket. O(1) average get, put, and remove; doubles past a 0.75 load factor.

/// fnv-1a, 32-bit, over the key's bytes. A `&str` is utf-8 already, so a key lands in the same
/// bucket here as in the other languages.
pub fn fnv1a(key: &str) -> u32 {
    let mut h: u32 = 2166136261;
    for &b in key.as_bytes() {
        // wrapping_mul is the mod 2^32 the hash wants. a plain * panics on overflow in debug builds
        h = (h ^ u32::from(b)).wrapping_mul(16777619);
    }
    h
}

/// String keys, integer values. Each bucket is a chain of (key, value) pairs. It starts with 8
/// buckets and never shrinks.
pub struct HashTable {
    buckets: Vec<Vec<(String, i64)>>,
    len: usize,
}

impl HashTable {
    /// Makes an empty table with 8 buckets.
    pub fn new() -> Self {
        Self {
            buckets: vec![Vec::new(); 8],
            len: 0,
        }
    }

    /// The number of keys.
    pub fn len(&self) -> usize {
        self.len
    }

    /// Whether there are no keys.
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// The number of buckets.
    pub fn bucket_count(&self) -> usize {
        self.buckets.len()
    }

    /// Inserts the key, or updates its value if it's already here.
    pub fn put(&mut self, key: &str, value: i64) {
        let b = self.bucket(key);
        if let Some(entry) = self.buckets[b].iter_mut().find(|(k, _)| k == key) {
            entry.1 = value; // an update: the size and the buckets stay
            return;
        }
        // a new key: grow first if it would push the load factor past 0.75
        if (self.len + 1) * 4 > self.buckets.len() * 3 {
            self.resize(self.buckets.len() * 2);
        }
        let b = self.bucket(key); // a new bucket count can move the key
        self.buckets[b].push((key.to_string(), value));
        self.len += 1;
    }

    /// The key's value, or `None` if the key isn't here.
    pub fn get(&self, key: &str) -> Option<i64> {
        self.buckets[self.bucket(key)]
            .iter()
            .find(|(k, _)| k == key)
            .map(|&(_, v)| v)
    }

    /// Drops the key. Returns false if it wasn't here.
    pub fn remove(&mut self, key: &str) -> bool {
        let b = self.bucket(key);
        match self.buckets[b].iter().position(|(k, _)| k == key) {
            Some(i) => {
                self.buckets[b].remove(i);
                self.len -= 1;
                true
            }
            None => false,
        }
    }

    fn bucket(&self, key: &str) -> usize {
        fnv1a(key) as usize % self.buckets.len()
    }

    /// Places every key again: the hash stays, but the bucket count changes.
    fn resize(&mut self, n: usize) {
        let old = std::mem::replace(&mut self.buckets, vec![Vec::new(); n]);
        for (key, value) in old.into_iter().flatten() {
            let b = self.bucket(&key);
            self.buckets[b].push((key, value)); // moved, not copied: no new strings
        }
    }
}

impl Default for HashTable {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    const DEMO: [(&str, i64); 6] = [
        ("cat", 1),
        ("dog", 2),
        ("owl", 3),
        ("bee", 4),
        ("ant", 5),
        ("cow", 6),
    ];

    #[test]
    fn fnv1a_vectors() {
        assert_eq!(fnv1a(""), 0x811c9dc5);
        assert_eq!(fnv1a("a"), 0xe40c292c);
        assert_eq!(fnv1a("foobar"), 0xbf9cf968);
        assert_eq!(fnv1a("é"), 0x1e9de8c1); // two bytes in utf-8: c3 a9
    }

    #[test]
    fn buckets_before_and_after_doubling() {
        for (key, bucket) in [
            ("cat", 7),
            ("bee", 7),
            ("dog", 1),
            ("owl", 5),
            ("ant", 6),
            ("cow", 0),
        ] {
            assert_eq!(fnv1a(key) % 8, bucket, "{key}");
        }
        // cat stays in 7, bee moves to 7 + 8
        assert_eq!((fnv1a("cat") % 16, fnv1a("bee") % 16), (7, 15));
    }

    #[test]
    fn starts_empty_with_8_buckets() {
        let mut t = HashTable::new();
        assert!(t.is_empty());
        assert_eq!((t.len(), t.bucket_count()), (0, 8));
        assert_eq!(t.get("cat"), None);
        assert!(!t.remove("cat"));
    }

    #[test]
    fn put_again_updates() {
        let mut t = HashTable::new();
        t.put("cat", 1);
        t.put("dog", 2);
        t.put("cat", 3);
        assert_eq!((t.get("cat"), t.len()), (Some(3), 2));
    }

    #[test]
    fn keys_in_one_bucket_are_both_found() {
        let mut t = HashTable::new();
        t.put("cat", 1);
        t.put("bee", 2); // same bucket as cat
        assert_eq!((t.get("cat"), t.get("bee")), (Some(1), Some(2)));
        assert!(t.remove("cat"));
        assert_eq!((t.get("cat"), t.get("bee")), (None, Some(2)));
    }

    #[test]
    fn the_7th_key_doubles_the_buckets() {
        let mut t = HashTable::new();
        for (key, value) in DEMO {
            t.put(key, value);
        }
        assert_eq!((t.bucket_count(), t.len()), (8, 6));
        t.put("cat", 9); // an update never resizes
        assert_eq!(t.bucket_count(), 8);
        t.put("yak", 7);
        assert_eq!((t.bucket_count(), t.len()), (16, 7));
        for (key, value) in DEMO.into_iter().skip(1).chain([("cat", 9), ("yak", 7)]) {
            assert_eq!(t.get(key), Some(value), "{key}");
        }
    }

    #[test]
    fn remove_twice() {
        let mut t = HashTable::new();
        t.put("cat", 1);
        assert!(t.remove("cat"));
        assert!(!t.remove("cat"));
        assert!(t.is_empty());
    }

    #[test]
    fn agrees_with_hashmap_over_2000_seeded_ops() {
        // xorshift32 seeded with 42, like the ring deque's test
        let mut state: u32 = 42;
        let mut next = || {
            state ^= state << 13;
            state ^= state >> 17;
            state ^= state << 5;
            state
        };
        let mut t = HashTable::new();
        let mut model = HashMap::new();
        for _ in 0..2000 {
            let key = format!("k{}", next() % 20);
            match next() % 3 {
                0 => {
                    let value = i64::from(next() % 1000);
                    t.put(&key, value);
                    model.insert(key, value);
                }
                1 => assert_eq!(t.get(&key), model.get(&key).copied()),
                _ => assert_eq!(t.remove(&key), model.remove(&key).is_some()),
            }
            assert_eq!(t.len(), model.len());
        }
    }
}
site/src/visuals/hash-table/hash-table.ts
/**
 * Hash table with separate chaining: fnv-1a picks the bucket. O(1) average get, put, and remove;
 * doubles past a 0.75 load factor.
 */
const encoder = new TextEncoder();

/** fnv-1a, 32-bit, over the key's utf-8 bytes. Every language on the page uses this same hash. */
export function fnv1a(key: string): number {
  let h = 2166136261;
  for (const b of encoder.encode(key)) h = Math.imul(h ^ b, 16777619) >>> 0;
  return h;
}

type Entry = { key: string; value: number };

export class HashTable {
  #buckets: Entry[][] = Array.from({ length: 8 }, () => []);
  #size = 0;

  get size(): number {
    return this.#size;
  }

  get bucketCount(): number {
    return this.#buckets.length;
  }

  /** Insert, or update the value if the key is already here. */
  put(key: string, value: number): void {
    const found = this.#chain(key).find((e) => e.key === key);
    if (found) {
      found.value = value; // an update: the size and the buckets stay
      return;
    }
    // a new key: grow first if it would push the load factor past 0.75
    if ((this.#size + 1) * 4 > this.#buckets.length * 3) this.#resize(this.#buckets.length * 2);
    this.#chain(key).push({ key, value });
    this.#size += 1;
  }

  get(key: string): number | undefined {
    return this.#chain(key).find((e) => e.key === key)?.value;
  }

  remove(key: string): boolean {
    const chain = this.#chain(key);
    const i = chain.findIndex((e) => e.key === key);
    if (i === -1) return false;
    chain.splice(i, 1);
    this.#size -= 1;
    return true;
  }

  /** The keys in each bucket, front to back. */
  chains(): string[][] {
    return this.#buckets.map((chain) => chain.map((e) => e.key));
  }

  #chain(key: string): Entry[] {
    return this.#buckets[fnv1a(key) % this.#buckets.length];
  }

  /** The hash stays, the bucket count changes, so every key is placed again. */
  #resize(n: number): void {
    const old = this.#buckets;
    this.#buckets = Array.from({ length: n }, () => []);
    for (const chain of old) for (const e of chain) this.#buckets[fnv1a(e.key) % n].push(e);
  }
}
c/algos/hash_table.c
/* hash table with separate chaining: fnv-1a picks the bucket. O(1) average get, put, and remove; doubles past a 0.75 load factor. */
#include "hash_table.h"

#include <stdlib.h>
#include <string.h>

uint32_t fnv1a(const char *key) {
    uint32_t h = 2166136261u;
    /* read bytes as unsigned char: a plain char can be signed, and then 0xc3 would xor in as -61 */
    for (const unsigned char *p = (const unsigned char *)key; *p; p++) {
        h ^= *p;
        h *= 16777619u; /* unsigned overflow wraps, which is the mod 2^32 the hash wants */
    }
    return h;
}

/* strdup isn't in c17, so the table copies keys itself */
static char *copy_key(const char *key) {
    size_t n = strlen(key) + 1;
    char *copy = malloc(n);
    if (copy) memcpy(copy, key, n);
    return copy;
}

static size_t bucket_of(const HashTable *t, const char *key) {
    return fnv1a(key) % t->cap;
}

/* where a new entry goes: the NULL at the end of the chain */
static Entry **chain_end(Entry **bucket) {
    while (*bucket) bucket = &(*bucket)->next;
    return bucket;
}

bool ht_init(HashTable *t) {
    t->buckets = calloc(8, sizeof *t->buckets); /* calloc: every chain starts NULL */
    t->len = 0;
    t->cap = t->buckets ? 8 : 0;
    return t->buckets != NULL;
}

void ht_free(HashTable *t) {
    for (size_t i = 0; i < t->cap; i++) {
        Entry *e = t->buckets[i];
        while (e) {
            Entry *next = e->next;
            free(e->key);
            free(e);
            e = next;
        }
    }
    free(t->buckets);
    t->buckets = NULL;
    t->len = t->cap = 0;
}

/* the hash stays and the bucket count changes, so every entry is placed again. the entries move
   as they are: no copying, just new next pointers */
static bool resize(HashTable *t, size_t n) {
    Entry **bigger = calloc(n, sizeof *bigger);
    if (!bigger) return false; /* t is untouched, so nothing is lost */
    for (size_t i = 0; i < t->cap; i++) {
        Entry *e = t->buckets[i];
        while (e) {
            Entry *next = e->next; /* save it: linking e into its new chain overwrites it */
            e->next = NULL;
            *chain_end(&bigger[fnv1a(e->key) % n]) = e;
            e = next;
        }
    }
    free(t->buckets);
    t->buckets = bigger;
    t->cap = n;
    return true;
}

bool ht_put(HashTable *t, const char *key, int value) {
    for (Entry *e = t->buckets[bucket_of(t, key)]; e; e = e->next) {
        if (strcmp(e->key, key) == 0) {
            e->value = value; /* an update: the size and the buckets stay */
            return true;
        }
    }
    /* a new key: grow first if it would push the load factor past 0.75 */
    if ((t->len + 1) * 4 > t->cap * 3 && !resize(t, t->cap * 2)) return false;
    Entry *e = malloc(sizeof *e);
    char *copy = copy_key(key);
    if (!e || !copy) {
        free(e);
        free(copy);
        return false;
    }
    e->key = copy;
    e->value = value;
    e->next = NULL;
    *chain_end(&t->buckets[bucket_of(t, key)]) = e;
    t->len++;
    return true;
}

bool ht_get(const HashTable *t, const char *key, int *out) {
    for (const Entry *e = t->buckets[bucket_of(t, key)]; e; e = e->next) {
        if (strcmp(e->key, key) == 0) {
            *out = e->value;
            return true;
        }
    }
    return false;
}

bool ht_remove(HashTable *t, const char *key) {
    /* p points at the link to the current entry (the bucket itself, or the one before's next), so
       unlinking is the same whether the entry is first in its chain or not */
    for (Entry **p = &t->buckets[bucket_of(t, key)]; *p; p = &(*p)->next) {
        if (strcmp((*p)->key, key) == 0) {
            Entry *gone = *p;
            *p = gone->next;
            free(gone->key);
            free(gone);
            t->len--;
            return true;
        }
    }
    return false;
}
swift/algos/HashTable.swift
/// hash table with separate chaining: fnv-1a picks the bucket. O(1) average get, put, and remove; doubles past a 0.75 load factor.
/// string keys, int values. each bucket is a chain of (key, value) entries.
public struct HashTable {
    private typealias Entry = (key: String, value: Int)
    // one chain of entries per bucket. starts at 8 buckets, never shrinks
    private var buckets: [[Entry]] = Array(repeating: [], count: 8)
    public private(set) var count = 0

    public init() {}

    public var bucketCount: Int { buckets.count }

    /// insert, or update the value if the key is already here.
    public mutating func put(_ key: String, _ value: Int) {
        let b = bucket(for: key)
        if let i = buckets[b].firstIndex(where: { $0.key == key }) {
            buckets[b][i].value = value // an update: the count and the buckets stay
            return
        }
        // a new key: grow first if it would push the load factor past 0.75
        if (count + 1) * 4 > bucketCount * 3 { resize(to: bucketCount * 2) }
        buckets[bucket(for: key)].append((key, value)) // look it up again: a resize can move the bucket
        count += 1
    }

    public func get(_ key: String) -> Int? {
        buckets[bucket(for: key)].first(where: { $0.key == key })?.value
    }

    public mutating func remove(_ key: String) -> Bool {
        let b = bucket(for: key)
        guard let i = buckets[b].firstIndex(where: { $0.key == key }) else { return false }
        buckets[b].remove(at: i)
        count -= 1
        return true
    }

    private func bucket(for key: String) -> Int {
        Int(fnv1a(key) % UInt32(buckets.count))
    }

    /// the hash stays, the bucket count changes, so every key is placed again.
    private mutating func resize(to n: Int) {
        let old = buckets
        buckets = Array(repeating: [], count: n)
        // old buckets in order, each chain front to back, so the new chains always come out the same
        for chain in old {
            for entry in chain {
                buckets[bucket(for: entry.key)].append(entry)
            }
        }
    }
}

/// fnv-1a, 32-bit, over the key's utf-8 bytes. every language on the page uses this same hash.
public func fnv1a(_ key: String) -> UInt32 {
    var h: UInt32 = 2166136261
    for b in key.utf8 {
        // &* wraps on overflow where plain * would crash, and that wrap is the mod 2^32
        h = (h ^ UInt32(b)) &* 16777619
    }
    return h
}
python/algos/hash_table.py
"""hash table with separate chaining: fnv-1a picks the bucket. O(1) average get, put, and remove; doubles past a 0.75 load factor."""

from __future__ import annotations


def fnv1a(key: str) -> int:
    """Hash the key's utf-8 bytes with 32-bit fnv-1a.

    Every language on the page uses this same hash, so a key lands in the same
    bucket in each one, and in the figure.
    """
    h = 2166136261
    for b in key.encode("utf-8"):
        # python ints grow instead of wrapping at 32 bits, so wrap by hand
        h = ((h ^ b) * 16777619) % 2**32
    return h


class HashTable:
    """String keys, int values. Each bucket is a chain of (key, value) pairs."""

    def __init__(self) -> None:
        # one list per bucket. [[]] * 8 would be the same list 8 times
        self._buckets: list[list[tuple[str, int]]] = [[] for _ in range(8)]
        self._size = 0

    def __len__(self) -> int:
        return self._size

    @property
    def bucket_count(self) -> int:
        return len(self._buckets)

    def put(self, key: str, value: int) -> None:
        """Insert, or update the value if the key is already here."""
        chain = self._chain(key)
        for i, (k, _) in enumerate(chain):
            if k == key:
                chain[i] = (key, value)  # an update: the size and the buckets stay
                return
        # a new key: grow first if it would push the load factor past 0.75
        if (self._size + 1) * 4 > self.bucket_count * 3:
            self._resize(2 * self.bucket_count)
            chain = self._chain(key)  # a new bucket count can move the key
        chain.append((key, value))
        self._size += 1

    def get(self, key: str) -> int | None:
        """Return the value, or None if the key isn't here (like dict.get)."""
        for k, value in self._chain(key):
            if k == key:
                return value
        return None

    def remove(self, key: str) -> bool:
        """Drop the key. Return False if it wasn't here."""
        chain = self._chain(key)
        for i, (k, _) in enumerate(chain):
            if k == key:
                del chain[i]
                self._size -= 1
                return True
        return False

    def _chain(self, key: str) -> list[tuple[str, int]]:
        return self._buckets[fnv1a(key) % self.bucket_count]

    def _resize(self, n: int) -> None:
        """Place every key again: the hash stays, but the bucket count changes."""
        old = self._buckets
        self._buckets = [[] for _ in range(n)]
        for chain in old:
            for key, value in chain:
                self._buckets[fnv1a(key) % n].append((key, value))

pitfalls

variants

practice

how real libraries do it

sources

  1. the fnv non-cryptographic hash algorithm (opens in a new tab): fnv-1a starts from the offset basis, 2166136261 for 32 bits, and for each byte xors it in and multiplies by the fnv prime, 16777619. go’s hash/fnv (opens in a new tab) credits glenn fowler, landon curt noll and phong vo, and its New32a is what the go tab’s test checks against. ↩

  2. HashMap.java (opens in a new tab) at jdk-21-ga: chained bins whose nodes keep their hash, a 0.75 default load factor, a table length that’s always a power of two, indexed by (n - 1) & hash, a hash() that xors the high 16 bits into the low ones, a resize that keeps each bin’s order while splitting it between index j and j + oldCap, and bins turned into red-black trees from 8 nodes once the table has at least 64 buckets, for worst-case O(log n) when keys have distinct hashes or are orderable. ↩ ↩2 ↩3 ↩4 ↩5

  3. dictobject.c (opens in a new tab) in cpython 3.15.0: the comments at the top describe the index table and the entries array kept in insertion order, and dummy slots that can’t become unused again or the probe sequence would lose track. further down: the probe recurrence with perturb, USABLE_FRACTION, the maximum load at 2/3, and me_hash in each general entry. ↩ ↩2 ↩3 ↩4

  4. HashTable.swift (opens in a new tab) in swift 6.4.1: a power-of-two bucket count, a maximum load factor of 3/4, inserts that take the next hole at or after the key’s ideal bucket, and a delete that moves out-of-place entries back into the hole. ↩ ↩2

  5. hash tables (opens in a new tab), section 3.4 of sedgewick and wayne’s algorithms, 4th edition: proposition m gives linear probing’s average probes for a hit and for a miss, assuming the hash spreads keys evenly over the slots. ↩

  6. hashable (opens in a new tab) in the python glossary: a hash that never changes during the object’s lifetime, equal objects with equal hashes, and mutable containers like lists that aren’t hashable. ↩ ↩2

  7. HashMap (opens in a new tab) in the rust docs: a port of google’s swisstable, hashed by default with a randomly seeded algorithm, currently siphash 1-3, chosen to resist hashdos attacks, and a logic error to change a key’s hash or equality while it’s in the map. ↩ ↩2 ↩3 ↩4

  8. Object.hashCode (opens in a new tab) in the java 21 docs: two objects that are equal by equals must return the same hash code. ↩

  9. for statements with range clause (opens in a new tab) in the go spec: the iteration order over maps isn’t specified and can change from one loop to the next. go1.27.2’s table.go (opens in a new tab) randomizes it by starting each loop at a random slot offset. ↩ ↩2

  10. mapping types (opens in a new tab) in the python docs: dictionaries preserve insertion order, guaranteed since 3.7, after being a cpython implementation detail in 3.6. ↩ ↩2

  11. scott a. crosby and dan s. wallach, denial of service via algorithmic complexity attacks (opens in a new tab), usenix security 2003: if every key hashes to the same bucket, inserting n of them takes O(n²). they attack the hash tables in two versions of perl, the squid web proxy and the bro intrusion detection system, and point to universal hashing as the fix. ↩

  12. PYTHONHASHSEED (opens in a new tab) and -R (opens in a new tab) in the python docs: str and bytes hashes get a random seed unless you set one, against inputs chosen to make building a dict O(n²). what’s new in 3.11 (opens in a new tab): str and bytes hash with siphash13 by default. ↩

  13. swiss tables design notes (opens in a new tab) from abseil: a metadata byte per slot with 7 bits of the hash and whether the slot is empty, deleted or full, 16 candidates checked at once with sse instructions, and a deleted slot that doesn’t stop a probe the way an empty one does. ↩

  14. the go 1.24 release notes (opens in a new tab): a new builtin map implementation based on swiss tables. ↩ ↩2

  15. Hasher.swift (opens in a new tab) and SipHash.swift (opens in a new tab) in swift 6.4.1: Hasher uses a per-execution seed set at startup, and its state compresses with one siphash round and finalizes with three: siphash-1-3. ↩