How does a Hash Map find one user profile out of 100 million in O(1) expected time—and what happens inside CPU cache lines when two keys collide on the exact same bucket?


In 30 Seconds

A Hash Map (Hash Table) [an associative key-value structure that maps arbitrary keys to array indices using a deterministic hash function] delivers O(1) expected time for insert, lookup, and delete. Under the hood, it passes your key through a hash function, masks the resulting integer into a power-of-two bucket array (hash & (capacity - 1)), and resolves collisions via Separate Chaining or cache-friendly Open Addressing.

The Real-World Analogy: Coat Check Tickets with Deterministic Cubby Math

Imagine a giant coat check room with 1,024 numbered cubbies (0 to 1023):

  • Instead of writing names in a ledger and scanning linearly when guests return, the attendant runs a quick math formula on your name (e.g., summing ASCII letter codes modulo 1024) to get your exact cubby number—say Cubby #412.
  • If two guests happen to hash to Cubby #412 (a hash collision), the attendant either hangs both coats on a mini-chain inside #412 (Separate Chaining) or places the second coat into the next open cubby #413 (Open Addressing / Linear Probing).

Under the Hood: Power-of-Two Bitmasking, Load Factor & Hash DoS Attacks

  1. Bitwise Masking Instead of Slow Division: CPU integer modulo (hash % capacity) takes ~15–40 clock cycles. By keeping table capacity a strict power of two ($2^k$), standard libraries (Python dict, Java HashMap, Rust HashMap) compute the bucket index in 1 single CPU cycle via hash & (capacity - 1)!
  2. Open Addressing (CPython dict) vs. Separate Chaining (Java HashMap): CPython stores compact entries directly inside a contiguous probe table—keeping adjacent probe slots inside the exact same 64-byte L1 CPU cache line! Java HashMap uses linked lists per bucket and upgrades long chains ($\ge 8$ nodes) into balanced Red-Black Trees to guarantee O(log N) worst-case lookup even under attack.
  3. Load Factor ($\alpha = N / \text{capacity}$) & Rehashing: Once the table exceeds ~66%–75% full (load factor $\alpha \approx 0.75$), collision chains lengthen rapidly. The table doubles its capacity and re-inserts every key (an O(N) spike that amortizes to O(1) per insert).
  4. SipHash & Randomized Hash Seeds (HashDoS Defense): If an attacker sends 100,000 crafted keys that all hash to bucket 0, an unprotected hash table degrades from $O(1)$ to $O(N^2)$ and freezes the server. Modern runtimes randomize the hash seed at startup (PYTHONHASHSEED / SipHash) so attackers cannot predict collisions!

Picture This

  Key: "alice" ---> hash("alice") = 0x7A3F9102
                    Mask (& 7)    = 2  (Bucket Index 2)

  OPEN ADDRESSING (Linear Probing in Contiguous RAM):
  Index:   [ 0 ]     [ 1 ]     [ 2 ]        [ 3 ]        [ 4 ]
  Entry:   Empty     Empty    "alice":95   "bob":88      Empty
                                ^            ^
                            Hash=2       Hash=2 (Collided! Probed +1 to Slot 3)

Show Me The Code

# Day 19: Open-Addressing Hash Map with Tombstone Deletion & Dynamic Resize in Python

class OpenAddressingHashMap:
    _TOMBSTONE = object()  # Sentinel marker so deleted slots don't break probe chains!

    def __init__(self, initial_cap=8):
        self._cap = initial_cap  # Always a power of 2
        self._keys = [None] * self._cap
        self._vals = [None] * self._cap
        self._size = 0

    def _probe(self, key):
        """Finds matching key slot or first available insertion slot."""
        mask = self._cap - 1
        idx = hash(key) & mask
        first_tombstone = None

        while True:
            curr_key = self._keys[idx]
            if curr_key is None:
                return first_tombstone if first_tombstone is not None else idx
            if curr_key is self._TOMBSTONE:
                if first_tombstone is None:
                    first_tombstone = idx
            elif curr_key == key:
                return idx
            idx = (idx + 1) & mask  # Linear probe wrap-around in 1 CPU cycle

    def _resize(self, new_cap):
        old_keys, old_vals = self._keys, self._vals
        self._cap = new_cap
        self._keys = [None] * new_cap
        self._vals = [None] * new_cap
        self._size = 0
        for k, v in zip(old_keys, old_vals):
            if k is not None and k is not self._TOMBSTONE:
                self.put(k, v)

    def put(self, key, val):
        if (self._size + 1) / self._cap > 0.66:
            self._resize(self._cap * 2)
        idx = self._probe(key)
        if self._keys[idx] is None or self._keys[idx] is self._TOMBSTONE:
            self._size += 1
        self._keys[idx] = key
        self._vals[idx] = val

    def get(self, key, default=None):
        idx = self._probe(key)
        if self._keys[idx] is not None and self._keys[idx] is not self._TOMBSTONE:
            return self._vals[idx]
        return default

    def delete(self, key):
        idx = self._probe(key)
        if self._keys[idx] is not None and self._keys[idx] is not self._TOMBSTONE:
            self._keys[idx] = self._TOMBSTONE  # Keep probe chain intact!
            self._vals[idx] = None
            self._size -= 1
            return True
        return False


if __name__ == "__main__":
    hm = OpenAddressingHashMap()
    hm.put("alice", 95)
    hm.put("bob", 88)
    print("alice:", hm.get("alice"))  # 95
    hm.delete("alice")
    print("bob after alice deleted:", hm.get("bob"))  # 88 (Probe chain preserved!)

Speed & Memory

OperationExpected TimeWorst CaseSpaceHardware & Algorithmic Why
get / put / deleteO(1)O(N)O(N)Load factor $\le 0.66$ keeps average probe length < 2 slots in L1 cache.

Traps To Avoid

  • Trap 1 (The Tombstone Bug): Setting a deleted slot to None in Open Addressing. Fix: Setting to None prematurely stops future searches for keys that collided past that slot—always write a _TOMBSTONE sentinel!
  • Trap 2: Using mutable objects (like a Python list) as dictionary keys. Fix: If a key mutates after insertion, its hash(key) changes and you can never find it again—convert lists to immutable tuples first!

Practice

  1. Easy: Find two indices in an unsorted array whose values sum to target in O(N) time (Two Sum).
  2. Medium: Group an array of strings into lists of anagrams in O(N * K) time using a 26-count tuple key.
  3. Hard: Find the length of the Longest Consecutive Sequence in an unsorted integer array in O(N) time (start counting streaks only from numbers x where x - 1 is NOT in the hash set!).

TL;DR

  • Hash Maps deliver O(1) expected lookups using power-of-two bitmasking (hash & (cap - 1)) and controlled load factors.
  • Open Addressing requires tombstone sentinels on deletion so probe chains stay unbroken.

References consulted: CPython Objects/dictobject.c & GeeksforGeeks Hashing Data Structure — referenced for verification — all content above is original.

Covered Log Update

Already covered: [Big-O notation, Arrays, Two Pointers, Strings, Sliding Window, Prefix Sums, Recursion basics, Singly Linked List, Doubly Linked List, Stack, Queue, Deque, Fast & Slow pointers, Binary Search, Bubble/Selection/Insertion Sort, Merge Sort, Quick Sort, Counting & Bucket Sort, Hashing & Hash Maps]