Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Lab · 30 min · revision 1

Lab: Build a Chained Hash Map

Implement a generic ChainedHashMap (put, get, delete, __len__, __iter__) with load-factor doubling and verify it differentially against Python dict across 10,000 random operations.

Contentsand lesson path

What you will learn

  • Implement a hash map with separate chaining and load-factor-based resizing that passes randomized tests against dict.

Prerequisites: Complexity Analysis

01. Goal and setup

Diagrams make separate chaining look straightforward, yet hand-written hash maps routinely fail three edge cases: updating an existing key appends a second tuple instead of overwriting, resizing copies entries into old indices instead of recomputing hash(key) % new_capacity, or deletion shifts bucket elements unnecessarily. Worse, three tiny manual tests can pass while a long interleaved sequence of inserts, updates, deletes, and resizes silently corrupts _size or leaves stale entries behind.

This lab demonstrates the full separate-chaining contract in working Python code and proves with differential testing that ChainedHashMap matches Python dict behaviour across 10,000 seeded random operations while keeping load_factor() <= 0.75.

Simplification note: our ChainedHashMap uses Python list buckets (list[list[tuple[K, V]]]) rather than linked-list nodes or CPython's compact open-addressing layout (dk_indices/dk_entries). That keeps bucket operations easy to inspect while enforcing every core invariant (hash(key) % capacity, collision chains, key equality, and load-factor doubling).

Environment: Python 3.12.13 with pytest 9.2.0 in an isolated virtual environment (newer pytest 9.x patch versions behave identically).

Terminal · create lab workspace
mkdir hashmap-lab && cd hashmap-lab
python3.12 -m venv .venv && source .venv/bin/activate
python -m pip install pytest

02. Step 1: implement ChainedHashMap with update-in-place and swap-pop delete

Create chained_map.py. Before running the script, verify the four invariants every method must uphold so ChainedHashMap matches Python dict semantics:

  • No duplicate keys in a bucket: put(key, value) scans bucket first; if existing_key == key, it overwrites bucket[i] = (key, value) and returns immediately without incrementing _size.
  • O(1) deletion inside a bucket: delete(key) copies bucket[-1] over slot i and calls bucket.pop(), avoiding O(chain_len) list shifting while decrementing _size by 1.
  • Independent bucket lists: __init__ and _resize allocate buckets via [[] for _ in range(cap)], never [[]] * cap (which aliases every bucket slot to the exact same inner list object).
  • Rehash on growth: when load_factor() > 0.75, _resize doubles capacity and recomputes hash(key) % new_capacity for every stored pair.

Predict before running: in the __main__ block below, m starts with initial_capacity = 4, inserts 5 distinct keys ("a".."e"), and updates "b" to 99. On which insert does load_factor() first exceed 0.75, and how many buckets will m hold at the end?

Python · chained_map.py
from collections.abc import Iterator
from typing import Generic, TypeVar

K = TypeVar("K")
V = TypeVar("V")


class ChainedHashMap(Generic[K, V]):
    def __init__(self, initial_capacity: int = 8) -> None:
        if initial_capacity < 1:
            raise ValueError("initial_capacity must be >= 1")
        buckets: list[list[tuple[K, V]]] = [[] for _ in range(initial_capacity)]
        self._buckets = buckets
        self._size = 0

    def __len__(self) -> int:
        return self._size

    def load_factor(self) -> float:
        return self._size / len(self._buckets)

    def _bucket(self, key: K) -> list[tuple[K, V]]:
        return self._buckets[hash(key) % len(self._buckets)]

    def put(self, key: K, value: V) -> None:
        bucket = self._bucket(key)
        for i, (existing_key, _) in enumerate(bucket):
            if existing_key == key:
                bucket[i] = (key, value)
                return
        bucket.append((key, value))
        self._size += 1
        if self.load_factor() > 0.75:
            self._resize(len(self._buckets) * 2)

    def get(self, key: K, default: V | None = None) -> V | None:
        for existing_key, value in self._bucket(key):
            if existing_key == key:
                return value
        return default

    def delete(self, key: K) -> bool:
        bucket = self._bucket(key)
        for i, (existing_key, _) in enumerate(bucket):
            if existing_key == key:
                bucket[i] = bucket[-1]
                bucket.pop()
                self._size -= 1
                return True
        return False

    def __iter__(self) -> Iterator[K]:
        for bucket in self._buckets:
            for key, _ in bucket:
                yield key

    def _resize(self, new_capacity: int) -> None:
        old_buckets = self._buckets
        self._buckets = [[] for _ in range(new_capacity)]
        for bucket in old_buckets:
            for key, value in bucket:
                idx = hash(key) % new_capacity
                self._buckets[idx].append((key, value))


if __name__ == "__main__":
    m: ChainedHashMap[str, int] = ChainedHashMap(initial_capacity=4)
    for idx, word in enumerate(["a", "b", "c", "d", "e"]):
        m.put(word, idx)
    m.put("b", 99)
    print("len:", len(m), "get('b'):", m.get("b"), "buckets:", len(m._buckets))
    print("delete('c'):", m.delete("c"), "len after:", len(m))
Terminal
python chained_map.py
Expected output
len: 5 get('b'): 99 buckets: 8
delete('c'): True len after: 4

Confirm your prediction: after 3 inserts, 3 / 4 = 0.75 (not strictly greater than 0.75). On the 4th insert ("d"), 4 / 4 = 1.0 > 0.75 triggers _resize(8). Notice "b" updated in place (get('b') == 99) and len(m) stayed 5 across that overwrite. Why did delete() overwrite bucket[i] with bucket[-1] and call bucket.pop() instead of bucket.pop(i)? Because entries inside a collision bucket have no required order, and swapping with the last slot runs in O(1) inside the bucket instead of shifting trailing entries left. (When i is already the last index, bucket[i] = bucket[-1] is a harmless self-copy before bucket.pop() removes it.)

What if you changed self.load_factor() > 0.75 to >= 0.75? With initial_capacity = 4, the 3rd insert (3 / 4 = 0.75) would trigger resizing one insert earlier, keeping peak load slightly lower while allocating 8 buckets sooner. Both thresholds keep put at O(1) amortised time because capacity doubles on every resize.

03. Step 2: differential and collision tests against dict with pytest

Three hand-picked unit tests easily miss subtle interactions between overwrites, deletions, and resizes. A differential test feeds the exact same seeded stream of 10,000 random put, get, and delete operations into both ChainedHashMap and Python's built-in dict (building on Type Hints and Tests with pytest), asserting that len, every get, load_factor() <= 0.75, and set(hm) == set(ref.keys()) match on every step. Comparing against a trusted reference lets random interleaving uncover state bugs—such as a stale _size counter or a missing key after the fourth resize—that isolated tests never exercise.

Look at two deliberate choices in test_chained_map.py. First, picking k = rng.randrange(400) across 10,000 operations guarantees heavy key reuse, frequent overwrites, deletions of both present and missing keys, and multiple resizes past initial_capacity = 8 (assert len(hm._buckets) > 8). Second, comparing set(hm) == set(ref.keys()) rather than lists reflects an important semantic difference: ChainedHashMap yields keys bucket-by-bucket (0 .. capacity - 1), whereas dict preserves insertion order.

We also add test_collisions_and_resize_preserve_keys using a custom _SameHashKey class whose __hash__ always returns 5. The first four keys share bucket 5 % 4 == 1; the fourth insert triggers _resize(8) and moves them to bucket 5 % 8 == 5, where the last two keys also land. Updating keys[1] and swap-popping keys[2] proves that updates, deletions, and resizes keep every colliding key intact without dropping or duplicating entries. Create test_chained_map.py and run pytest.

Python · test_chained_map.py
import random

from chained_map import ChainedHashMap


class _SameHashKey:
    def __init__(self, name: str) -> None:
        self.name = name

    def __eq__(self, other: object) -> bool:
        return isinstance(other, _SameHashKey) and self.name == other.name

    def __hash__(self) -> int:
        return 5


def test_chained_hashmap_matches_dict_10k_ops() -> None:
    rng = random.Random(2026)
    hm: ChainedHashMap[int, int] = ChainedHashMap(initial_capacity=8)
    ref: dict[int, int] = {}
    for step in range(10_000):
        op = rng.randrange(3)
        k = rng.randrange(400)
        if op == 0:
            hm.put(k, step)
            ref[k] = step
        elif op == 1:
            assert hm.get(k) == ref.get(k)
        else:
            assert hm.delete(k) == (k in ref)
            ref.pop(k, None)
        assert len(hm) == len(ref)
        assert hm.load_factor() <= 0.75
    assert len(hm._buckets) > 8
    assert set(hm) == set(ref.keys())
    for k, v in ref.items():
        assert hm.get(k) == v


def test_collisions_and_resize_preserve_keys() -> None:
    hm: ChainedHashMap[_SameHashKey, int] = ChainedHashMap(initial_capacity=4)
    keys = [_SameHashKey(f"k{i}") for i in range(6)]
    for i, k in enumerate(keys):
        hm.put(k, i * 10)
    hm.put(keys[1], 999)
    assert hm.delete(keys[2]) is True
    assert hm.delete(keys[2]) is False
    assert len(hm) == 5
    assert len(hm._buckets) == 8
    assert hm.get(keys[1]) == 999
    assert hm.get(keys[2]) is None
    assert hm.get(keys[5]) == 50
Terminal
pytest -v test_chained_map.py
Expected output (excerpt: pytest header and timing summary omitted)
test_chained_map.py::test_chained_hashmap_matches_dict_10k_ops PASSED    [ 50%]
test_chained_map.py::test_collisions_and_resize_preserve_keys PASSED     [100%]

04. Check your understanding

Practice check · 2 questions

ChainedHashMap invariants

Diagnose edge cases in your chained hash map.

Q1. In `delete()`, why can `bucket[i] = bucket[-1]; bucket.pop()` safely overwrite slot `i` with the last entry instead of calling `bucket.pop(i)`?
Q2. Suppose `__init__` mistakenly wrote `self._buckets = [[]] * initial_capacity`. What happens on the very first `hm.put("a", 1)`?
Practice only: not graded, not saved, not evidence.

05. Apply it

Extend ChainedHashMap to handle None values cleanly and match dict more closely: add __contains__(self, key: K) -> bool, keys(), items(), and __getitem__ (raising KeyError on missing keys, or using a private _MISSING = object() sentinel inside get). Also verify what happens if caller code mutates ChainedHashMap during for k in hm:: _resize replaces self._buckets, so add a version counter that raises RuntimeError if mutated during iteration, just like Python dict. Expand test_chained_map.py to verify None values and key in hm.

Next, apply standard-library hash structures (dict, set, Counter, defaultdict) to solve algorithmic problems in Counting, Grouping and Complement Lookups.

06. Review prompt

Without looking back:

  1. What two invariants must put preserve when inserting a key that is already in the map?
  2. Why does test_chained_hashmap_matches_dict_10k_ops interleave put, get, and delete with len and set(hm) checks rather than testing each method in isolation?
  3. Why does [[]] * capacity break a hash table?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check