Sign in

Data Structures

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.

Plain words. One step at a time. Nothing here assumes you already know the idea.

The idea

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.

See it

Imagine a wall of post-office mailboxes, where each mailbox has a fixed numeric slot number.

1 of 4

You will need. Basic knowledge of arrays and indexing · Understanding of modulo arithmetic · Familiarity with writing functions and classes in Python

One pass

Step 1 of 4

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.

Smallest version

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

# Demonstration
table = MinimalHashTable(size=5)
table.set("apple", 42)
table.set("banana", 99)
assert table.get("apple") == 42
assert table.get("banana") == 99
assert table.get("cherry") is None

Keep these

  • 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.

Try one

Two sum problem

easy

Start the five-step lesson

Also on MonksBit