Hash Functions and Collision Handling — Chaining vs Open Addressing — Complete Beginner Guide
Learning Objectives
- Describe qualities of a good hash function
- Explain why collisions are unavoidable
- Implement separate chaining with lists
- Implement open addressing with linear probing
- Compare the two collision strategies
What Is a Hash Function?
A hash function takes a key and returns an integer index inside a fixed bucket array. Great functions are fast, deterministic, and spread keys evenly across buckets.
| Quality | Meaning |
|---|---|
| Deterministic | Same key always maps the same way |
| Uniform | Keys spread across many buckets |
| Fast | Computed quickly for hot paths |
| Avalanche small | Tiny key change flips the index |
def hash_key(key, bucket_count):
# Simple toy hash for learning
value = 0
for ch in str(key):
value = (value * 31 + ord(ch)) % 1000003
return value % bucket_count
print(hash_key("alice", 16))
print(hash_key("bob", 16))
Production systems use stronger functions such as murmur hash or sip hash to avoid patterns and attacks.
What Is a Collision?
A collision happens when two different keys hash to the same bucket. With finite buckets and open-ended keys, collisions are guaranteed over time.
You cannot avoid collisions. You can only handle them well.
Strategy One: Separate Chaining
Each bucket holds a small container, usually a linked list or dynamic array. Matching keys live together in that chain.
class ChainingHashTable:
def __init__(self, size=8):
self.size = size
self.buckets = [[] for _ in range(size)]
def _index(self, key):
return hash(key) % self.size
def put(self, key, value):
index = self._index(key)
bucket = self.buckets[index]
for i, pair in enumerate(bucket):
if pair[0] == key:
bucket[i] = (key, value)
return
bucket.append((key, value))
def get(self, key):
index = self._index(key)
for k, v in self.buckets[index]:
if k == key:
return v
raise KeyError(key)
def delete(self, key):
index = self._index(key)
bucket = self.buckets[index]
for i, pair in enumerate(bucket):
if pair[0] == key:
del bucket[i]
return
table = ChainingHashTable()
table.put("a", 1)
table.put("b", 2)
table.put("a", 10)
print(table.get("a")) # 10
Chaining Notes
| Aspect | Behavior |
|---|---|
| Bucket growth | Each bucket expands freely |
| Load factor limit | Often near one or higher |
| Extra memory | Pointers and list overhead |
| Deletion | Simple once pair is found |
| Cache locality | Weaker due to scattered nodes |
Strategy Two: Open Addressing
All entries live inside the bucket array itself. On collision, probing finds the next open slot.
| Probe Rule | Idea |
|---|---|
| Linear probing | Check next slot in a fixed step |
| Quadratic probing | Step by growing squares |
| Double hashing | Use a second hash for the step |
class LinearProbeTable:
def __init__(self, size=8):
self.size = size
self.keys = [None] * size
self.values = [None] * size
def _index(self, key):
return hash(key) % self.size
def put(self, key, value):
index = self._index(key)
while self.keys[index] is not None:
if self.keys[index] == key:
self.values[index] = value
return
index = (index + 1) % self.size
self.keys[index] = key
self.values[index] = value
def get(self, key):
index = self._index(key)
while self.keys[index] is not None:
if self.keys[index] == key:
return self.values[index]
index = (index + 1) % self.size
raise KeyError(key)
probe = LinearProbeTable()
probe.put("x", 7)
probe.put("y", 8)
print(probe.get("x"), probe.get("y"))
Open Addressing Notes
| Aspect | Behavior |
|---|---|
| Storage | Single contiguous array |
| Load factor limit | Usually below zero point seven five |
| Clustering | Linear probing can pack long runs |
| Deletion | Needs tombstones to keep probes valid |
| Cache locality | Strong due to dense layout |
Chaining versus Open Addressing
| Criteria | Chaining | Open Addressing |
|---|---|---|
| Implementation ease | Easier | Harder |
| Memory overhead | Higher | Lower |
| Very high load | Still works | Degrades fast |
| Deletion | Straightforward | Needs tombstones |
| Typical use | Language dictionaries | Compact fixed tables |
Complexity
Both strategies keep average operations at O(1). Bad spread or very high load pushes searches toward O(n) because buckets or probe runs grow long.
Collision Lab
Run a tiny collision lab to build intuition. Hash several keys into only four buckets and count how many buckets receive more than one key. Then repeat with sixteen buckets and watch the cluster thin out. Larger bucket counts lower average chain length but cost more memory.
Next, turn on open addressing and insert the same keys. Notice how one crowded region slows every later probe that hashes nearby. That clustering effect is why linear probing usually keeps a lower load factor than chaining.
def naive_hash(key, buckets):
return sum(ord(ch) for ch in key) % buckets
keys = ["aa", "ab", "ba", "bb", "cd"]
for size in (4, 16):
table = [[] for _ in range(size)]
for k in keys:
table[naive_hash(k, size)].append(k)
longest = max(len(b) for b in table)
print(size, longest, [b for b in table if b])
If you see long chains, either improve spread with a better function or grow the table. Both strategies restore the average O(1) promise.
Key Takeaways
💡
- Collisions happen when two keys share a bucket index
- Good hashes are deterministic, fast, and well spread
- Chaining stores overflow entries in per-bucket lists
- Open addressing keeps every entry inside the main array
- Average cost stays O(1) when load and clustering stay controlled
Practice Questions
- List three properties you want in a hash function and explain each.
- Compare chaining and open addressing for a table that must support easy deletion.
- Why does linear probing risk clustering, and how does quadratic probing reduce it?
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions