AlgoViz

Hash implementation

medium 18 min

A hash table is an array of buckets plus a hash function that turns each key into an index.

Video lesson · Chapter 1 of 6

Two numbers in one pigeonhole

0:00 / 5:11

Implementing a hash table — The costume booth collision

1:27Reel

Read caption

Mika traces a chained hash bucket, compares exact ticket numbers and rehashes the costumes into a larger table. Hash to a bucket. Match the key. Rehash when capacity changes.

How it works

Step through the idea, or press Play.

Step 1 of 3

Hash the key. A hash function turns any key into a number, then mod m makes it an index into m buckets

Understand it

Start here

What a hash table is

An array gives O(1)O(1) access when you know the index. A hash table extends that to any key, such as a name, a word or a tuple, by computing the index from the key itself. It keeps an array of mm buckets, and a key lives in bucket hash(key) % m. Python's dict and set, Java's HashMap and C++'s unordered_map are all hash tables. This page builds one from scratch; for how to use them in problems see hashing in practice, and for the set and map interfaces see sets and maps.

Every operation starts the same way
  1. 1Key"apple"
  2. 2hash()a big integer
  3. 3mod man index 0..m−1
  4. 4Bucketinsert, find or delete here

Insert, search and delete differ only in what they do once they reach the bucket.

The three pillars

  • Hash

    A function turns the key into an index. Same key, same index, every time.

  • Store

    The entry goes into the bucket at that index: one array access, no searching.

  • Resolve

    When two keys share a bucket, chain them in a list or probe for another slot.

Step 1

The hash function

A hash function maps a key to an integer; reducing it mod mm gives a bucket. For an integer key the simplest choice is the key itself. For a string, treat the characters as digits of a number in base 31 (a polynomial hash). Multiplying before adding makes position matter, so "cat" and "act" differ. Computing it left to right with Horner's rule, and taking the mod at each step, keeps every intermediate value small.

Integer and string hashes

h(k)=k mod mh(s)=(∑i=0L−1si⋅31 L−1−i) mod m,computed as h←(31h+si) mod mh(k) = k \bmod m \qquad h(s) = \Big(\sum_{i=0}^{L-1} s_i \cdot 31^{\,L-1-i}\Big) \bmod m, \quad \text{computed as } h \leftarrow (31h + s_i) \bmod m
sis_i is the code of the ii-th character and LL the length, so hashing a string costs O(L)O(L). Java's String.hashCode uses exactly this polynomial (with 32-bit overflow instead of the mod).

What makes a hash function good

PropertyMeaningWhy it matters
DeterministicSame key gives the same hash every timeOtherwise you could never find a key again
UniformKeys spread evenly over the bucketsShort chains and short probe runs: the O(1)O(1) average depends on it
FastO(L)O(L) in the key length, few operations per characterIt runs on every single operation
AvalancheA small change in the key changes the hash a lotSimilar keys (user1, user2) must not cluster
Proven choices: the polynomial rolling hash, FNV-1a, MurmurHash, SipHash (Python's string hash, which also resists deliberate collisions).
Python
def bucket_index(key, m):    if isinstance(key, int):        return key % m                  # never negative in Python when m > 0    h = 0    for ch in key:        h = (h * 31 + ord(ch)) % m      # Horner's rule, reduced every step    return hprint(bucket_index("cat", 7), bucket_index("act", 7))   # 3 5: order mattersprint(bucket_index(12, 7), bucket_index(19, 7))         # 5 5: a collisionprint(bucket_index(-3, 7))                              # 4, not -3def sum_hash(s, m):                     # a poor hash for comparison    return sum(map(ord, s)) % mprint(sum_hash("cat", 7), sum_hash("act", 7))           # 4 4: anagrams always collide
Bucket indexes for integers and strings, and why the multiply-by-31 step matters.
Edit and run it in your browser

Worked example

Hashing "cat" into 7 buckets

insert("cat", 5) into a table of size 7

  1. 1

    Get the character codes

    ord('c') = 99, ord('a') = 97, ord('t') = 116.

  2. 2

    Run Horner's rule mod 7

    h=99 mod 7=1h = 99 \bmod 7 = 1, then (31⋅1+97) mod 7=2(31 \cdot 1 + 97) \bmod 7 = 2, then (31⋅2+116) mod 7=178 mod 7=3(31 \cdot 2 + 116) \bmod 7 = 178 \bmod 7 = 3.

  3. 3

    Check against the full value

    99⋅312+97⋅31+116=9826299 \cdot 31^2 + 97 \cdot 31 + 116 = 98262 and 98262 mod 7=398262 \bmod 7 = 3: the same index, without the big number.

  4. 4

    Store in bucket 3

    Bucket 3 is empty, so ("cat", 5) becomes its first entry. Any later get("cat") recomputes 3 and looks only there.

CharacterCode31·h + codemod 7
c9931⋅0+99=9931 \cdot 0 + 99 = 991
a9731⋅1+97=12831 \cdot 1 + 97 = 1282
t11631⋅2+116=17831 \cdot 2 + 116 = 1783
The running value never exceeds 31⋅631 \cdot 6 plus the largest character code, whatever the string length.

Step 2

Collisions are guaranteed

There are far more possible keys than buckets, so by the pigeonhole principle some keys must share an index. Worse, collisions show up long before the table is full. This is the birthday paradox: with 365 possible birthdays, 23 people already give better than even odds that two share one.

Chance that n keys in m buckets avoid each other

P(no collision)=∏i=0n−1(1−im)≈e−n(n−1)/(2m)P(\text{no collision}) = \prod_{i=0}^{n-1}\Big(1 - \frac{i}{m}\Big) \approx e^{-n(n-1)/(2m)}
For 4 keys in 7 buckets: 7⋅6⋅5⋅474=8402401≈0.35\frac{7 \cdot 6 \cdot 5 \cdot 4}{7^4} = \frac{840}{2401} \approx 0.35, so a collision is about 65% likely. The first collision is expected after only about πm/2≈1.25m\sqrt{\pi m / 2} \approx 1.25\sqrt{m} keys.

Two families of collision handling

Chaining keeps colliding keys outside the array; open addressing finds them another slot inside it.

Strategy 1

Separate chaining

Each bucket holds a small list (a linked list, or a Python list) of the entries that hashed there. Insert hashes to the bucket, scans the chain, updates the key if it is there and appends it otherwise. Search walks only that chain. Delete unlinks the entry. Java's HashMap works this way.

put(key, value) with chaining

get is the same walk returning the value (or None at the end); remove is the same walk unlinking the entry.
Python
class HashTable:    """Hash table with separate chaining."""    def __init__(self, size=7):        self.size = size        self.buckets = [[] for _ in range(size)]   # one empty chain per bucket    def _hash(self, key):        return hash(key) % self.size    def insert(self, key, value):        bucket = self.buckets[self._hash(key)]        for i, (k, v) in enumerate(bucket):            if k == key:                bucket[i] = (key, value)           # existing key: update                return        bucket.append((key, value))                # new key: extend the chain    def get(self, key):        for k, v in self.buckets[self._hash(key)]:            if k == key:                return v        return None    def delete(self, key):        bucket = self.buckets[self._hash(key)]        for i, (k, v) in enumerate(bucket):            if k == key:                del bucket[i]                return True        return Falseht = HashTable()for k, v in [(5, "apple"), (12, "banana"), (7, "cherry"), (19, "date")]:    ht.insert(k, v)print(ht.buckets[5])        # [(5, 'apple'), (12, 'banana'), (19, 'date')]print(ht.get(12), ht.get(26))   # banana Noneht.delete(5)print(ht.buckets[5])        # [(12, 'banana'), (19, 'date')]
A minimal chained hash table: insert or update, get and delete.
Edit and run it in your browser

Strategy 2

Open addressing and probing

Open addressing stores every entry in the array itself. If the home slot h(k)h(k) is taken, the key follows a probe sequence to other slots until it finds an empty one, and a search follows the same sequence until it finds the key or an empty slot. No pointers, and neighbouring slots share cache lines, so it is fast while the table is sparse. Python's dict uses open addressing.

Probe sequences, for attempt i = 0, 1, 2, ...

linear: (h+i) mod mquadratic: (h+i2) mod mdouble: (h1(k)+i⋅h2(k)) mod m\text{linear: } (h + i) \bmod m \qquad \text{quadratic: } (h + i^2) \bmod m \qquad \text{double: } (h_1(k) + i \cdot h_2(k)) \bmod m
Double hashing needs h2(k)≠0h_2(k) \ne 0 and coprime with mm so the sequence visits every slot; with mm prime, any h2h_2 in 1..m−11..m-1 works, such as h2(k)=5−(k mod 5)h_2(k) = 5 - (k \bmod 5) for m=7m = 7.
MethodProsConsBest for
ChainingSimple, works at any load factor, easy deletionExtra memory for pointers, cache unfriendlyUnknown or changing data sizes
Linear probingMost cache friendly, no extra memoryPrimary clustering: runs of full slots grow and merge; needs tombstonesKnown maximum size, when CPU cache matters
Quadratic probingBreaks up primary clustersSecondary clustering (same home, same path); may miss free slots above α=1/2\alpha = 1/2Moderate load factors with a prime mm
Double hashingEach key has its own step, close to ideal spreadingNeeds a second good hash; probes jump around memoryHigh load factors, high performance
With a prime mm and α≤1/2\alpha \le 1/2, the first ⌈m/2⌉\lceil m/2 \rceil quadratic probes hit distinct slots, so an empty slot is always found. A prime alone does not make quadratic probing cover the whole table.

Insert with linear probing

Inserting 21 into slots [14, 8, -, ...] of size 7: home 0 holds 14, slot 1 holds 8, slot 2 is empty, so 21 lands there after 3 probes. A real table resizes long before it is full.

Deletion

Tombstones

Searching in open addressing stops at the first empty slot, since an empty slot means the key was never placed further along. So deleting by emptying a slot breaks every probe run that passed through it. Instead, write a tombstone (a DELETED marker): searches step over it, inserts may reuse it. In slots [14, 8, 21, 1] with 21 homed at 0, deleting 8 by emptying slot 1 would make get(21) stop at slot 1 and wrongly report it missing.

get(key) when tombstones exist

An insert follows the same walk but remembers the first tombstone it passes; if the key turns out to be absent, it is stored in that tombstone's slot.
Python
DELETED = object()            # unique marker: not a key, not emptyclass LinearProbing:    def __init__(self, m=7):        self.m = m        self.table = [None] * m    def put(self, key, value):        i, first_tomb = key % self.m, None        while self.table[i] is not None:            slot = self.table[i]            if slot is DELETED:                if first_tomb is None:                    first_tomb = i          # reusable, but keep looking for key            elif slot[0] == key:                self.table[i] = (key, value)                return            i = (i + 1) % self.m        self.table[first_tomb if first_tomb is not None else i] = (key, value)    def get(self, key):        i = key % self.m        while self.table[i] is not None:            slot = self.table[i]            if slot is not DELETED and slot[0] == key:                return slot[1]            i = (i + 1) % self.m            # step over tombstones        return None    def remove(self, key):        i = key % self.m        while self.table[i] is not None:            slot = self.table[i]            if slot is not DELETED and slot[0] == key:                self.table[i] = DELETED                return True            i = (i + 1) % self.m        return False    def show(self):        return ["DEL" if s is DELETED else (s and s[0]) for s in self.table]t = LinearProbing()for k in [14, 8, 21, 1]:    t.put(k, str(k))print(t.show())          # [14, 8, 21, 1, None, None, None]t.remove(8)print(t.show())          # [14, 'DEL', 21, 1, None, None, None]print(t.get(21))         # 21: found by stepping over the tombstonet.put(22, "22")          # 22 % 7 == 1: reuses the tombstoneprint(t.show())          # [14, 22, 21, 1, None, None, None]
Linear probing with tombstones (fixed size, no resize, for clarity).
Edit and run it in your browser

Analysis

Load factor and expected cost

Load factor

α=nm=keys storedbuckets\alpha = \frac{n}{m} = \frac{\text{keys stored}}{\text{buckets}}
With chaining, α\alpha can exceed 1. With open addressing, α≤1\alpha \le 1 always, and tables resize far earlier: Java's HashMap at 0.75 (chaining), Python's dict at 2/3 (open addressing).

Separate chaining, assuming uniform hashing

E[chain length]=α,miss: Θ(1+α),hit: 1+α2−α2n≈1+α2\mathbb{E}[\text{chain length}] = \alpha, \qquad \text{miss: } \Theta(1 + \alpha), \qquad \text{hit: } 1 + \frac{\alpha}{2} - \frac{\alpha}{2n} \approx 1 + \frac{\alpha}{2}
Each of the nn keys lands in a given bucket with probability 1/m1/m, so a bucket expects n/m=αn/m = \alpha keys. A miss reads one whole chain; a hit reads about half of one, plus the key itself.

Open addressing: expected probes

uniform miss≤11−α,uniform hit≤1αln⁡11−α,linear hit≈12(1+11−α),linear miss≈12(1+1(1−α)2)\text{uniform miss} \le \frac{1}{1-\alpha}, \quad \text{uniform hit} \le \frac{1}{\alpha}\ln\frac{1}{1-\alpha}, \quad \text{linear hit} \approx \frac{1}{2}\Big(1 + \frac{1}{1-\alpha}\Big), \quad \text{linear miss} \approx \frac{1}{2}\Big(1 + \frac{1}{(1-\alpha)^2}\Big)
Why 11−α\frac{1}{1-\alpha}: each probe finds a full slot with probability about α\alpha, so the number of probes is geometric, 1+α+α2+⋯=11−α1 + \alpha + \alpha^2 + \dots = \frac{1}{1-\alpha}. The linear-probing formulas are Knuth's; clustering adds the square.
αChaining hitIdeal probing missLinear hitLinear missVerdict
0.251.121.331.171.39Very few collisions, but much wasted space
0.51.2521.52.5Comfortable for any scheme
0.71.353.332.176.06Upper end of the sweet spot for open addressing
0.91.45105.550.5Probing collapses; resize well before this
Expected comparisons per search. Chaining degrades gently with α\alpha; open addressing hits a cliff as α→1\alpha \to 1, which is why it keeps more empty space.

Growth

Resizing and rehashing

To keep α\alpha bounded as keys arrive, the table grows: when α\alpha passes the threshold it allocates about twice as many buckets and reinserts every entry. Each key must be rehashed, because its index hash(k) % m depends on mm: with m=4m = 4 key 15 is in bucket 3, with m=8m = 8 it belongs in bucket 7. This is the same doubling trick as a dynamic array, with a rehash in place of a plain copy.

Insert with automatic resizing

Some tables also shrink (for example to m/2 when α falls below 1/4) so memory follows the data down.

Doubling makes resizing O(1) amortised

total work for n inserts  ≤  n+∑j=0⌊log⁡2n⌋2j  <  n+2n=3n  ⟹  O(1) per insert\text{total work for } n \text{ inserts} \;\le\; n + \sum_{j=0}^{\lfloor \log_2 n \rfloor} 2^j \;<\; n + 2n = 3n \;\Longrightarrow\; O(1) \text{ per insert}
Resizes happen at sizes 1, 2, 4, 8, ... and each copies the keys present at that moment, a geometric series below 2n2n. Growing by a fixed amount (say +10 buckets) instead would make the total O(n2)O(n^2).

Worst case

When O(1) turns into O(n)

The O(1)O(1) is an average that assumes keys spread evenly. Keys 3, 10, 17 and 24 in a table of 7 all have remainder 3, so they share one bucket and get(17) walks 3, 10, 17 like a linked list. If all nn keys collide, every operation costs O(n)O(n). Load factor alone does not save you: keys 1, 2, 8, 15, 22, 29 give α=6/7\alpha = 6/7 but one chain of 5.

OperationAverageWorstNotes
InsertO(1)O(1) amortisedO(n)O(n)Occasional O(n)O(n) resize, spread over many inserts
SearchO(1)O(1)O(n)O(n)Worst case: every key in one chain or one probe run
DeleteO(1)O(1)O(n)O(n)Chaining unlinks; open addressing leaves a tombstone
ResizeO(n)O(n)O(n)O(n)Rehashes every key once
SpaceO(n)O(n)O(n)O(n)Plus empty buckets: about n/αn/\alpha slots in total
Hashing a key of length LL adds O(L)O(L) to every row; it is usually treated as constant.

In practice

How Python's dict works

CPython's dict is an open-addressing table with a compact layout (since 3.6). A dense entries array stores (hash, key, value) in insertion order, which is why dicts iterate in insertion order. A separate sparse indices array, sized a power of two (at least 8), holds positions into entries. Lookups probe indices with a perturbed sequence, i←(5i+1+perturb) mod 2ki \leftarrow (5i + 1 + \text{perturb}) \bmod 2^k with perturb\text{perturb} shifted right 5 bits each step, so all the bits of the hash get used. Deleting leaves a dummy (a tombstone) in indices, and the table grows when about 2/3 of it is in use.

d[key] in CPython, simplified

Comparing the stored hash first is cheap and skips most == calls. set uses a similar open-addressing table without the compact entries array.
Python
import sysprint(hash(42), hash(-1), hash(2**61 - 1))   # 42 -2 0: ints hash mod 2**61 - 1print(hash("cat"))      # differs between runs: str hashing is saltedd, last = {}, sys.getsizeof({})for k in range(20):    d[k] = k    size = sys.getsizeof(d)    if size != last:                          # the table was resized        print("grew at", len(d), "keys:", last, "->", size, "bytes")        last = sizeprint(list({"cy": 3, "ann": 9, "bo": 5}))    # ['cy', 'ann', 'bo']: insertion orderclass Key:    def __init__(self, a, b):        self.a, self.b = a, b    def __eq__(self, other):        return (self.a, self.b) == (other.a, other.b)    def __hash__(self):                       # equal objects must hash equally        return hash((self.a, self.b))print({Key(1, 2): "x"}[Key(1, 2)])           # x
Peeking at Python's hashing: ints hash to themselves, str hashes change between runs, and the dict grows in steps.
Edit and run it in your browser

Recap

Choosing a design and key takeaways

Chaining vs open addressing

AspectSeparate chainingOpen addressing
LayoutArray of listsOne array plus a probe sequence
Cache behaviourWorse: nodes scatteredBetter: neighbouring slots
DeleteEasy: unlinkNeeds tombstones
High load factorDegrades gently, α>1\alpha > 1 allowedDegrades fast, α<1\alpha < 1 required
Typical resize pointα>0.75\alpha > 0.75α>2/3\alpha > 2/3 or 0.70.7
Used byJava HashMap, C++ unordered_mapPython dict and set, Rust HashMap, Go maps (since 1.24)

Hash table vs alternatives

StructureSearchInsertDeleteOrdered?
Hash tableO(1)O(1) avgO(1)O(1) avgO(1)O(1) avgNo
Balanced BSTO(log⁡n)O(\log n)O(log⁡n)O(\log n)O(log⁡n)O(\log n)Yes
Sorted arrayO(log⁡n)O(\log n)O(n)O(n)O(n)O(n)Yes
Linked listO(n)O(n)O(1)O(1) at the headO(n)O(n)No
Hash table costs are averages; the worst case is O(n)O(n). Need order, ranges or floor and ceiling? See sets and maps.

Do

  • Use a hash that spreads keys and mixes in every character's position.
  • Check for an existing key before appending, so put updates.
  • Resize by doubling and rehash every key when α\alpha passes the threshold.
  • Use tombstones for deletion in open addressing, and rebuild when they pile up.

Avoid

  • Constant or sum-of-characters hashes.
  • Letting α\alpha grow without bound, or running open addressing near α=1\alpha = 1.
  • Copying buckets by position on resize.
  • Mutable keys, or __eq__ without a matching __hash__.

Key points

  • A hash table is an array of mm buckets; a key lives at hash(key) % m, so insert, search and delete jump straight to it.
  • Good hash functions are deterministic, uniform, fast and avalanche; strings use a polynomial hash with base 31 via Horner's rule.
  • Collisions are guaranteed (birthday paradox). Chaining keeps a list per bucket; open addressing probes linearly, quadratically or by double hashing.
  • Open addressing deletes with tombstones, because a search stops at the first empty slot.
  • Load factor α=n/m\alpha = n/m: chains average α\alpha long; probing costs about 11−α\frac{1}{1-\alpha}, exploding as α→1\alpha \to 1.
  • Doubling and rehashing keeps α\alpha bounded at O(1)O(1) amortised per insert; the worst case is O(n)O(n) when keys collide.
  • Python's dict: compact open addressing, perturbed probing, growth at about 2/3 full, insertion-ordered entries.

Sources