Hash tables from scratch, resolving collisions to building dynamic maps
Learn how hash tables map arbitrary keys to array indices, handle collisions gracefully, and resize dynamically for constant-time lookups.
MonksBit Desk
November 17, 2026 · 9 min read · 109 views
Read
A hash table is a data structure that stores associative key-value pairs by using a mathematical function to compute an index from each key into an array of buckets. This structure allows programs to insert, retrieve, and delete values in constant average time.
You will need. Basic knowledge of arrays and indexing · Understanding of modulo arithmetic · Familiarity with writing functions and classes in Python
The full lesson
Level 1 · Beginner: Core concept of hashing keys to array indices
An array lets you retrieve any element immediately if you know its numerical index. However, programs often need to look up data using non-numeric labels such as usernames or email addresses. A hash table bridges this gap by translating non-numeric keys into valid array indices.
This translation is performed by a hash function. A hash function accepts a key as input and outputs a deterministic integer. To keep this integer within the bounds of a fixed-size array, the table applies the modulo operator using the total number of slots in the array as the divisor.
Consider an array with four slots and three keys: apple, banana, and cherry. Suppose a simple hash function sums the ASCII values of the characters in each string. The sum for apple is 530. Dividing 530 by 4 yields a remainder of 2, so apple is stored at index 2. The sum for banana is 609, which modulo 4 yields index 1. The sum for cherry is 647, which modulo 4 yields index 3. Every key lands in an assigned slot.
The simplest hash table stores values directly in an array using this calculation. When looking up apple, the table computes 530 modulo 4 again, inspects index 2, and returns the stored value.
A minimal fixed-size hash table without collision resolution
class MinimalHashTable: def __init__(self, size=10): self.size = size self.slots = [None] * size def _hash(self, key): total = sum(ord(char) for char in str(key)) return total % self.size def set(self, key, value): index = self._hash(key) self.slots[index] = (key, value) def get(self, key): index = self._hash(key) pair = self.slots[index] if pair is not None and pair[0] == key: return pair[1] return None# Demonstrationtable = MinimalHashTable(size=5)table.set("apple", 42)table.set("banana", 99)assert table.get("apple") == 42assert table.get("banana") == 99assert table.get("cherry") is None
Key takeaways
- Hash tables use hash functions to convert arbitrary keys into integer indices.
- The modulo operator bounds the resulting integer to the size of the backing array.
- Keys that produce identical indices will overwrite each other unless collisions are handled.
Level 2 · Intermediate: Resolving collisions with separate chaining and dynamic resizing
Because the universe of possible keys is far larger than the number of array slots, multiple distinct keys inevitably produce the same array index. This event is called a collision. A robust hash table must store multiple entries that share an index without losing data.
Separate chaining is a collision resolution technique where each array slot holds a bucket containing a list of key-value pairs. When inserting a pair, the table checks whether the key already exists in that slot's list. If found, the value is updated; if not, the new pair is appended to the list.
As more items are inserted, buckets grow longer and search operations slow down to linear time. The ratio of stored items to array capacity is called the load factor. When the load factor exceeds a threshold, typically 0.75, the table must allocate a larger backing array and rehash every existing key into the new array.
Testing this implementation requires verifying empty table lookups, key updates, collision handling when distinct keys map to the same bucket, key deletions, and automatic resizing when the load threshold is crossed.
A complete chained hash table with dynamic resizing and deletion
class ChainedHashTable: def __init__(self, initial_capacity=8, load_factor_threshold=0.75): self.capacity = initial_capacity self.threshold = load_factor_threshold self.count = 0 self.buckets = [[] for _ in range(self.capacity)] def _hash(self, key): return hash(key) % self.capacity def _resize(self, new_capacity): old_buckets = self.buckets self.capacity = new_capacity self.buckets = [[] for _ in range(new_capacity)] self.count = 0 for bucket in old_buckets: for k, v in bucket: self.set(k, v) def set(self, key, value): if (self.count + 1) / self.capacity > self.threshold: self._resize(self.capacity * 2) index = self._hash(key) bucket = self.buckets[index] for i, (k, v) in enumerate(bucket): if k == key: bucket[i] = (key, value) return bucket.append((key, value)) self.count += 1 def get(self, key): index = self._hash(key) bucket = self.buckets[index] for k, v in bucket: if k == key: return v raise KeyError(key) def delete(self, key): index = self._hash(key) bucket = self.buckets[index] for i, (k, v) in enumerate(bucket): if k == key: del bucket[i] self.count -= 1 return raise KeyError(key)# Verificationht = ChainedHashTable(initial_capacity=2)ht.set("alpha", 1)ht.set("beta", 2)ht.set("gamma", 3) # Triggers resizeassert ht.get("alpha") == 1assert ht.get("beta") == 2assert ht.get("gamma") == 3ht.delete("beta")assert ht.count == 2
Key takeaways
- Separate chaining keeps a collection of key-value pairs at each array index.
- The load factor measures how crowded the table is by dividing count by capacity.
- Dynamic resizing preserves average constant-time performance by doubling capacity and rehashing items.
Level 3 · Advanced: Open addressing, linear probing, and practical hash table trade-offs
Separate chaining requires extra pointer allocations for bucket nodes or sub-lists, which reduces CPU cache efficiency. An alternative design is open addressing, where all entries reside directly within a single flat array. When a collision occurs, the algorithm probes forward across sequential indices until it locates an empty slot.
Linear probing is the simplest open addressing scheme: if index h is occupied, the algorithm inspects h + 1, h + 2, and so forth, wrapping around the end of the array. Retrieval follows the same probe sequence until it either finds the matching key or encounters an empty slot, which proves the key is absent.
Deletion in open addressing presents a subtle challenge. Removing an entry by clearing a slot to None creates a false empty gap that interrupts probe chains for keys inserted later. To fix this, deleted slots must be marked with a special sentinel value called a tombstone, allowing lookups to continue scanning past them while letting new insertions overwrite them.
Open addressing is susceptible to primary clustering, where contiguous blocks of occupied slots merge into long chains, degrading search times to linear complexity. Real-world systems like Python dictionaries and PHP internal arrays use hybrid strategies: Python uses a pseudo-random perturbation sequence over an open-addressed compact array, whereas PHP maintains a separate packed array coupled with an indirect hash bucket array to preserve insertion order.
Open addressing with linear probing and tombstone deletion
class LinearProbingMap: _DELETED = object() def __init__(self, capacity=8): self.capacity = capacity self.keys = [None] * capacity self.values = [None] * capacity self.count = 0 def _hash(self, key): return hash(key) % self.capacity def _resize(self, new_capacity): old_keys = self.keys old_values = self.values self.capacity = new_capacity self.keys = [None] * new_capacity self.values = [None] * new_capacity self.count = 0 for k, v in zip(old_keys, old_values): if k is not None and k is not self._DELETED: self.set(k, v) def set(self, key, value): if (self.count + 1) / self.capacity > 0.65: self._resize(self.capacity * 2) index = self._hash(key) first_tombstone = None while self.keys[index] is not None: if self.keys[index] is self._DELETED: if first_tombstone is None: first_tombstone = index elif self.keys[index] == key: self.values[index] = value return index = (index + 1) % self.capacity target_index = first_tombstone if first_tombstone is not None else index self.keys[target_index] = key self.values[target_index] = value self.count += 1 def get(self, key): index = self._hash(key) start = index while self.keys[index] is not None: if self.keys[index] == key: return self.values[index] index = (index + 1) % self.capacity if index == start: break raise KeyError(key) def delete(self, key): index = self._hash(key) start = index while self.keys[index] is not None: if self.keys[index] == key: self.keys[index] = self._DELETED self.values[index] = None self.count -= 1 return index = (index + 1) % self.capacity if index == start: break raise KeyError(key)# Verificationm = LinearProbingMap(capacity=4)m.set("k1", "v1")m.set("k2", "v2")m.delete("k1")assert m.get("k2") == "v2"m.set("k3", "v3")assert m.get("k3") == "v3"
Key takeaways
- Open addressing avoids extra pointer allocations by storing all entries directly in the main table.
- Linear probing requires tombstone sentinels during deletion to avoid terminating searches prematurely.
- High load factors in open addressing cause primary clustering, requiring resizing at lower thresholds like 0.65.
Complexity
- Time: Best case O(1), Average case O(1), Worst case O(n)
- Space: O(n) auxiliary space
Assuming a well-distributed hash function and an enforced load factor ceiling, slot lookups take constant time on average. If all keys collide into a single chain or probe sequence, every operation degrades to linear time O(n). Auxiliary space is linear in the number of stored keys and allocated capacity.
Common mistakes
- Mutating an object after using it as a key, which alters its hash code and makes it unfindable.
- Failing to implement tombstones during open addressing deletions, causing future lookups of existing keys to terminate early.
- Neglecting to rehash all existing keys during table resize, which leaves keys stranded at wrong modulo boundaries.
- Using a predictable, poor hash function that maps disproportionate numbers of keys to identical buckets.
Practice problems
- Two sum problem (easy). Hint: Store each visited number and its array index in a hash map, then check if the complement exists on each iteration.
- Group anagrams (medium). Hint: Transform each string into a canonical representation, such as sorted characters or character counts, and use that as the map key.
- Implement an LRU cache (hard). Hint: Combine a hash map for constant-time key lookups with a doubly linked list to track access order.
Summary
Hash tables deliver average constant-time associative lookups by translating keys into array indices with hash functions and modulo arithmetic. Collisions can be solved externally using separate chaining or internally via open addressing with tombstones. Maintaining performance requires monitoring the load factor and periodically allocating larger tables to rehash entries.
Was this helpful?
Comments (0)
Sign in or create an account to join the conversation.
- No comments yet. Be the first!