AlgoViz

Hash implementation

medium 18 min

A hash table is an array of buckets plus a hash function that turns each key into an index.

See it run

Hash a key to a bucket, resolve collisions by chaining or probing, delete with tombstones, and resize when the load factor climbs.

Operations

Hash function

Turn a key into a bucket index. Integers use k mod m; strings use a polynomial hash with base 31, reduced mod m at every step (Horner's rule).

Step 1 of 7

Hash "cat" into 7 buckets

charord31·h + ordmod 7
c99??
a97??
t116??

The table has m = 7 buckets, indices 0 to 6. We need one number for the key "cat", and it must be the same number every time. Start with h = 0 and read the characters left to right.

Step 1: Hash "cat" into 7 buckets

def bucket_index(key, m):    if isinstance(key, int):        return key % m              # Python's % is never negative for m > 0    h = 0    for ch in key:        h = (h * 31 + ord(ch)) % m  # Horner's rule, reduced as we go    return hprint(bucket_index("cat", 7))   # 3print(bucket_index(12, 7))      # 5
Time
O(L) for a key of length L
Space
O(1)
integer key
one mod: O(1)
Python caches
str hash computed once

A good hash function spreads keys evenly. Multiplying by a prime such as 31 mixes in each character's position, so anagrams and similar keys land in different buckets.

In the real world

The same hash implementation doing real jobs. Pick one and step through it.

Animal sounds keyed by name, hashed with h = (31h + ord(c)) mod 7. Two names collide and share a chain.

Step 1 of 5

cat → bucket 3

1st2nd
bucket 0··
bucket 1··
bucket 2··
bucket 3cat: meow·
bucket 4··
bucket 5··
bucket 6··

c, a, t give running values 1, 2, 3 mod 7, so "cat" goes to bucket 3.

Step 1: cat → bucket 3

sounds = HashMap(7)sounds.put("cat", "meow")    # bucket 3sounds.put("dog", "woof")    # bucket 6sounds.put("bird", "chirp")  # bucket 1sounds.put("cow", "moo")     # bucket 6: collides with dogprint(sounds.get("dog"))     # woof

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • A hash function that does not spread keys

    critical

    If every key gets the same index, every key sits in one chain or one probe run, and every operation costs O(n). Summing character codes is almost as bad: anagrams always collide.

    Wrong
    def bucket(key, m):    return 0                          # every key in bucket 0def bucket_sum(s, m):    return sum(map(ord, s)) % m       # "cat", "act", "tac" collide
    Right
    def bucket(s, m):    h = 0    for ch in s:        h = (h * 31 + ord(ch)) % m    # position matters    return h
  • Emptying a slot on delete in open addressing

    critical

    A search stops at the first empty slot. Clearing a slot in the middle of a probe run makes every key after it unreachable. Write a tombstone instead.

    Wrong
    def remove(self, key):    i = self._find(key)    if i is not None:        self.table[i] = None          # breaks later probe chains
    Right
    DELETED = object()def remove(self, key):    i = self._find(key)    if i is not None:        self.table[i] = DELETED       # searches step over it
  • Appending a key that is already there

    major

    put must update an existing key. Appending blindly stores two entries for one key: size is wrong, memory grows, and a later delete removes only one copy.

    Wrong
    def put(self, key, value):    self.buckets[hash(key) % self.m].append((key, value))
    Right
    def put(self, key, value):    bucket = self.buckets[hash(key) % self.m]    for j, (k, _) in enumerate(bucket):        if k == key:            bucket[j] = (key, value)            return    bucket.append((key, value))
  • Never resizing

    major

    With a fixed m, the load factor grows with every insert and so do the chains. A table of 16 buckets holding a million keys averages 62,500 comparisons per lookup.

    Wrong
    def put(self, key, value):    self._insert(key, value)    self.n += 1                       # m never changes
    Right
    def put(self, key, value):    self._insert(key, value)    self.n += 1    if self.n / self.m > 0.75:        self._resize(2 * self.m)
  • Copying buckets by position when resizing

    critical

    A key's index is hash(key) % m, so it changes when m changes. Moving bucket 3 of the old table to bucket 3 of the new one leaves keys where lookups will never look.

    Wrong
    def _resize(self, new_m):    new = [[] for _ in range(new_m)]    for i, bucket in enumerate(self.buckets):        new[i] = bucket               # wrong buckets for the new m    self.buckets, self.m = new, new_m
    Right
    def _resize(self, new_m):    new = [[] for _ in range(new_m)]    for bucket in self.buckets:        for k, v in bucket:            new[hash(k) % new_m].append((k, v))   # rehash every key    self.buckets, self.m = new, new_m
  • Hashing a field that can change

    major

    If a key's hash depends on mutable state and that state changes after insertion, the key sits in the bucket for its old hash and becomes unfindable. Hash only immutable fields, and keep __eq__ and __hash__ consistent.

    Wrong
    class Point:    def __init__(self, x, y):        self.x, self.y = x, y    def __hash__(self):        return hash((self.x, self.y))    def __eq__(self, o):        return (self.x, self.y) == (o.x, o.y)p = Point(1, 2); seen = {p}p.x = 5print(p in seen)                      # False
    Right
    from dataclasses import dataclass@dataclass(frozen=True)               # immutable, hash and eq generatedclass Point:    x: int    y: intseen = {Point(1, 2)}print(Point(1, 2) in seen)            # True

Interview tips

  • How to explain it

    • An array of m buckets plus a hash function: index = hash(key) mod m. Jumping straight to the index is what makes it O(1).
    • Collisions are unavoidable. Chaining keeps a list per bucket; open addressing probes for another slot (linear, quadratic, double hashing).
    • Load factor α = n/m drives the cost: chains average α long, probing costs about 1/(1−α). Resize (double m, rehash everything) to keep α bounded, giving O(1) amortised.
    • Mention the trade-off: O(1) average time for O(n) extra space, and O(n) worst case when keys collide.
  • Interview habits

    • Always ask whether a hash map is allowed: it is often the key to the optimal solution.
    • Know when to use a hash set (membership only) versus a hash map (a value per key).
    • Be ready to implement one from scratch (Design HashMap) and to discuss collision handling and when to use each.
    • Practise: Two Sum, Design HashMap, Group Anagrams, Longest Consecutive Sequence, LRU Cache, Insert Delete GetRandom O(1).
  • Memory tricks

    • HASH: Hash the key to an index, Access the bucket directly, Search the chain if there was a collision, Handle the insert, find or delete.
    • Three pillars: Hash (key to index), Store (at the bucket), Chain (if it collides).
    • Rhyme: "Hash the key, find the spot, chain them up when there's a lot, O(1) time is what we've got."
    • The library story: a wizard turns each title into a shelf number; books sent to the same shelf stand in a row.
  • Patterns behind the code

    • Modulo hashing: hash(key) % m turns any integer into a valid index.
    • Separate chaining: a list per bucket, scanned key by key.
    • Dynamic resizing: double m when α passes 0.75 (chaining) or about 2/3 (open addressing).
    • Key iteration: compare each entry in the chain or probe run with ==, never by hash alone.