🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Hash Functions and Collision Handling — Chaining vs Open Addressing — Complete Beginner Guide

Data Structures FoundationsHash Functions and Collision Handling — Chaining vs Open Addressing🟢 Free Lesson

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.

QualityMeaning
DeterministicSame key always maps the same way
UniformKeys spread across many buckets
FastComputed quickly for hot paths
Avalanche smallTiny key change flips the index
python
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.

python
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

AspectBehavior
Bucket growthEach bucket expands freely
Load factor limitOften near one or higher
Extra memoryPointers and list overhead
DeletionSimple once pair is found
Cache localityWeaker 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 RuleIdea
Linear probingCheck next slot in a fixed step
Quadratic probingStep by growing squares
Double hashingUse a second hash for the step
python
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

AspectBehavior
StorageSingle contiguous array
Load factor limitUsually below zero point seven five
ClusteringLinear probing can pack long runs
DeletionNeeds tombstones to keep probes valid
Cache localityStrong due to dense layout

Chaining versus Open Addressing

CriteriaChainingOpen Addressing
Implementation easeEasierHarder
Memory overheadHigherLower
Very high loadStill worksDegrades fast
DeletionStraightforwardNeeds tombstones
Typical useLanguage dictionariesCompact 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.

python
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

  1. List three properties you want in a hash function and explain each.
  2. Compare chaining and open addressing for a table that must support easy deletion.
  3. 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

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. 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

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. 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

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids 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
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Data Structures Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement