Skip to content

Hash Map - A Warehouse You Search by Name Tag ​

Here we build by hand what Python's dict does internally.

How It Works ​

  1. Hash function: turns the key (a string) into a number
  2. That number modulo the number of buckets = the storage location (room number)
  3. Lookups use the same calculation → check only that one room → O(1) on average
python
def _hash(self, key: str) -> int:
    """Turns a key string into a room number (bucket index)"""
    h = 0
    for ch in key:            # for each character
        h = (h * 31 + ord(ch)) % self._bucket_count  # multiply-by-a-prime trick for even distribution
    return h

Collisions and Chaining ​

Sometimes different keys get assigned the same room number (a collision). Chaining = lining up multiple entries as a linked list inside that room. → As the requirements recommend, you can reuse the doubly linked list built earlier.

Load Factor and Resizing ​

  • Load factor = number of stored items ÷ number of buckets (how crowded the rooms are)
  • Above 0.75, collisions become frequent and things slow down, so double the buckets and redistribute every item (rehash)

Note: For the bucket array, using a list is allowed only at the level of "a fixed-length array with index access." Implementing put/get with a dict is forbidden!

Summary ​

ConceptPlain-language summary
Hash mapA warehouse where you calculate the name tag and go straight to the spot. On a collision, line items up inside the room (chaining)

Source: Codyssey-B1/B5-1