Hash implementation
medium 18 minA 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
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.
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 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 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.
- 1Key"apple"
- 2hash()a big integer
- 3mod man index 0..m−1
- 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 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
String.hashCode uses exactly this polynomial (with 32-bit overflow instead of the mod).What makes a hash function good
| Property | Meaning | Why it matters |
|---|---|---|
| Deterministic | Same key gives the same hash every time | Otherwise you could never find a key again |
| Uniform | Keys spread evenly over the buckets | Short chains and short probe runs: the average depends on it |
| Fast | in the key length, few operations per character | It runs on every single operation |
| Avalanche | A small change in the key changes the hash a lot | Similar keys (user1, user2) must not cluster |
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 collideWorked example
Hashing "cat" into 7 buckets
insert("cat", 5) into a table of size 7
- 1
Get the character codes
ord('c') = 99,ord('a') = 97,ord('t') = 116. - 2
Run Horner's rule mod 7
, then , then .
- 3
Check against the full value
and : the same index, without the big number.
- 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.
| Character | Code | 31·h + code | mod 7 |
|---|---|---|---|
| c | 99 | 1 | |
| a | 97 | 2 | |
| t | 116 | 3 |
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
Two families of collision handling
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
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')]Strategy 2
Open addressing and probing
Open addressing stores every entry in the array itself. If the home slot 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, ...
| Method | Pros | Cons | Best for |
|---|---|---|---|
| Chaining | Simple, works at any load factor, easy deletion | Extra memory for pointers, cache unfriendly | Unknown or changing data sizes |
| Linear probing | Most cache friendly, no extra memory | Primary clustering: runs of full slots grow and merge; needs tombstones | Known maximum size, when CPU cache matters |
| Quadratic probing | Breaks up primary clusters | Secondary clustering (same home, same path); may miss free slots above | Moderate load factors with a prime |
| Double hashing | Each key has its own step, close to ideal spreading | Needs a second good hash; probes jump around memory | High load factors, high performance |
Insert with linear probing
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
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]Analysis
Load factor and expected cost
Load factor
HashMap at 0.75 (chaining), Python's dict at 2/3 (open addressing).Separate chaining, assuming uniform hashing
Open addressing: expected probes
| α | Chaining hit | Ideal probing miss | Linear hit | Linear miss | Verdict |
|---|---|---|---|---|---|
| 0.25 | 1.12 | 1.33 | 1.17 | 1.39 | Very few collisions, but much wasted space |
| 0.5 | 1.25 | 2 | 1.5 | 2.5 | Comfortable for any scheme |
| 0.7 | 1.35 | 3.33 | 2.17 | 6.06 | Upper end of the sweet spot for open addressing |
| 0.9 | 1.45 | 10 | 5.5 | 50.5 | Probing collapses; resize well before this |
Growth
Resizing and rehashing
To keep bounded as keys arrive, the table grows: when 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 : with key 15 is in bucket 3, with 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
Doubling makes resizing O(1) amortised
Worst case
When O(1) turns into O(n)
The 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 keys collide, every operation costs . Load factor alone does not save you: keys 1, 2, 8, 15, 22, 29 give but one chain of 5.
| Operation | Average | Worst | Notes |
|---|---|---|---|
| Insert | amortised | Occasional resize, spread over many inserts | |
| Search | Worst case: every key in one chain or one probe run | ||
| Delete | Chaining unlinks; open addressing leaves a tombstone | ||
| Resize | Rehashes every key once | ||
| Space | Plus empty buckets: about slots in total |
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, with 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
== calls. set uses a similar open-addressing table without the compact entries array.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)]) # xRecap
Choosing a design and key takeaways
Chaining vs open addressing
| Aspect | Separate chaining | Open addressing |
|---|---|---|
| Layout | Array of lists | One array plus a probe sequence |
| Cache behaviour | Worse: nodes scattered | Better: neighbouring slots |
| Delete | Easy: unlink | Needs tombstones |
| High load factor | Degrades gently, allowed | Degrades fast, required |
| Typical resize point | or | |
| Used by | Java HashMap, C++ unordered_map | Python dict and set, Rust HashMap, Go maps (since 1.24) |
Hash table vs alternatives
| Structure | Search | Insert | Delete | Ordered? |
|---|---|---|---|---|
| Hash table | avg | avg | avg | No |
| Balanced BST | Yes | |||
| Sorted array | Yes | |||
| Linked list | at the head | No |
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 passes the threshold.
- Use tombstones for deletion in open addressing, and rebuild when they pile up.
Avoid
- Constant or sum-of-characters hashes.
- Letting grow without bound, or running open addressing near .
- Copying buckets by position on resize.
- Mutable keys, or
__eq__without a matching__hash__.
Key points
- A hash table is an array of 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 : chains average long; probing costs about , exploding as .
- Doubling and rehashing keeps bounded at amortised per insert; the worst case is when keys collide.
- Python's dict: compact open addressing, perturbed probing, growth at about 2/3 full, insertion-ordered entries.