Skip to content
Visual explainer 2h 30m to learn 4 steps

Hash functions

Explain what makes a good hash function and why keys must be immutable.

By Invicly Tech, , in Data Structures & Algorithms. About 12 minutes to read.

Topic 15 of 54

In short

A hash function turns a key into an integer that is then reduced to a bucket index. A good one is deterministic, fast and spreads keys uniformly so few keys share a bucket. Keys must not change after insertion, otherwise their hash changes and they can no longer be found.

Explained simply

Think of a big coat room with 100 numbered hooks. When a guest arrives, you do not search for a free hook at random. You use a rule, for example the last two digits of their phone number, to pick a hook. Later, you use the same rule to find their coat at once. A hash function is that rule for data.

A hash function takes a key, such as a word or a number, and turns it into an integer. The program then shrinks that integer to fit the table, usually with the remainder after division (h % size). The result is the bucket, the slot where the item lives.

A good hash function has three jobs. It must always give the same answer for the same key (deterministic). It must be fast. And it must spread keys evenly, so a few buckets do not get crowded while others stay empty.

Two different keys sometimes land in the same bucket. This is called a collision, and it cannot be avoided completely, because there are more possible keys than buckets. A good hash function just makes collisions rare and random, and the table has a plan for handling them.

There is one strict rule: a key must not change after you store it. If it changes, its hash changes, and the table looks in the wrong bucket. That is why Python lets you use strings, numbers and tuples as dict keys, but not lists.

Press Play on a diagram to walk through it one step at a time.

FlowFrom key to bucket
  1. Step 1
    Key

    'cat'

  2. Step 2
    Hash

    hash('cat') gives a large integer.

  3. Step 3
    Reduce

    index = h % capacity

  4. Step 4
    Bucket

    Store or look up the entry there.

CompareWeak versus good string hash
Sum of character codes
  • 'abc', 'bca', 'cab' all collide
  • Ignores order
  • Small range for short words
  • Easy to attack
Polynomial mod prime
  • Order changes the value
  • Spreads over the full range
  • Rolls in O(1) per step
  • Random base resists attacks

In depth

From any key to a bucket index

Hashing happens in two stages. First, the key becomes a fixed-size integer, often 64 bits. Second, that integer is reduced to an index in the range 0 to capacity - 1.

The common reduction is h % capacity. Many real tables (Python dict, Java HashMap) use a capacity that is a power of two, so the reduction becomes h & (capacity - 1), which keeps only the low bits and is faster than division. The danger: if keys differ only in their high bits, they all collide. So these tables mix the bits first. Java's HashMap XORs the top 16 bits into the low 16 bits, and Python's dict feeds the high bits into its probe sequence.

Another classic method is multiplicative (Fibonacci) hashing: multiply the key by 2654435769 (about 2^32 divided by the golden ratio), keep 32 bits, and take the top r bits for a table of 2^r slots.

  • Stage 1: key to integer
  • Stage 2: integer to index
  • Power-of-two capacity: index = h & (cap - 1)
  • Prime capacity with % is more forgiving of weak hashes
FlowInside a dict lookup
  1. 1
    Key

    For example the string 'cat'.

  2. 2
    hash(key)

    A 64-bit integer, cached on str objects.

  3. 3
    Mix bits

    Spread high bits into low bits.

  4. 4
    Mask

    h & (capacity - 1) gives the slot.

  5. 5
    Compare

    Check hash and then == on the stored key.

Uniformity, collisions and the birthday effect

With n keys and m buckets, a uniform hash puts n / m keys in each bucket on average. That ratio is the load factor, and it decides how fast lookups are.

Collisions come sooner than intuition says. This is the birthday paradox: in a room of only 23 people, the chance that two share a birthday is over 50 percent, even though there are 365 days. In general, you expect the first collision after about the square root of m keys. For a 32-bit hash that is roughly 77,000 keys for a 50 percent chance. This is why tables must handle collisions, and why you should never treat a 32-bit hash as a unique ID.

A weak hash makes things worse. Summing character codes, for example, gives 'abc', 'acb' and 'cba' the same value, so all anagrams collide.

  • Load factor = n / m
  • Expect a collision after about sqrt(m) keys
  • Order-blind hashes (like sums) collide on anagrams

Polynomial rolling hashes for strings

Treat a string as a number in base B: h(s) = s[0]*B^(k-1) + s[1]*B^(k-2) + ... + s[k-1], all taken mod a large prime M. Because each position has a different power of B, order matters, so 'abc' and 'cba' differ.

The trick is the rolling update. When a window of length k slides one step right, you remove the leftmost character's term, shift everything by multiplying by B, and add the new character: h = ((h - s[i]*B^(k-1)) * B + s[i+k]) mod M. Each step is O(1), so you can hash every window of a text of length n in O(n) total.

Rabin-Karp search uses this: compare window hashes with the pattern hash, and only check characters when hashes match. Expected time is O(n + k); the worst case is O(n * k) if many hashes match falsely. Pick a random base, or use two moduli, to make false matches very unlikely.

  • Typical choice: B = 31 or random, M = 10^9 + 7
  • Precompute B^(k-1) mod M once
  • Equal hash is a hint, not a proof: verify

Why keys must be immutable

A table stores each entry in the bucket chosen by the key's hash at insertion time. If the key later changes, its new hash points to a different bucket. Lookups now search the wrong place, and the old entry becomes a ghost: still taking space, but unreachable.

Python protects you for built-in types. list, dict and set have __hash__ set to None, so hash([1, 2]) raises TypeError. A tuple is hashable only if everything inside it is hashable, so hash((1, [2])) also fails. Use tuple or frozenset as keys instead.

For your own classes, the default hash is based on object identity, which is safe. If you define __eq__, Python sets __hash__ to None unless you also define __hash__. When you do, hash exactly the fields that __eq__ compares, and never change those fields while the object is inside a set or dict. A frozen dataclass does this for you.

  • Rule: a == b must imply hash(a) == hash(b)
  • Unequal objects may share a hash
  • @dataclass(frozen=True) gives a matching __hash__

Hash flooding and Python's randomised hashes

If an attacker knows your hash function, they can send thousands of keys that all land in one bucket, for example as form fields in a web request. Every insert then scans a long chain, turning O(1) into O(n) and a request into a CPU-burning O(n^2) job. This is called hash flooding, a denial-of-service attack.

The defence is a keyed hash: mix a secret random seed into the hash. Since Python 3.3, str and bytes hashes are randomised per process, and since 3.4 they use SipHash with a secret random key. Run python -c "print(hash('cat'))" twice and you get two different numbers. Set the environment variable PYTHONHASHSEED=0 to turn this off for reproducible debugging.

Integers are not randomised: hash(42) is 42. Note also that hash(1) == hash(1.0) == hash(True), because they compare equal, so they act as the same dict key.

Learn it in 4 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Map keys to bucket indexes~40m
  2. 2
    Explain uniformity and determinism~40m
  3. 3
    Hash strings with polynomial rolling hashes~40m
  4. 4
    Explain why mutable keys break hashing~40m

Key points

  • Computing a hash is O(length of key), treated as O(1) for small keys.
  • Equal keys must produce equal hashes; unequal keys may collide.
  • Polynomial rolling hashes update in O(1) as a window slides, enabling Rabin-Karp.
  • Python randomises string hashes per process to resist collision attacks.

Key terms

Tap a card to flip it. 0/4 known

Examples

python
def poly_hash(s, base=31, mod=10**9 + 7):
    h = 0
    for ch in s:
        h = (h * base + ord(ch)) % mod
    return h

print(poly_hash('abc'), poly_hash('acb'))   # different values
print(hash((1, 2)) == hash((1, 2)))         # True
# hash([1, 2]) raises TypeError: lists are mutable

Seeing a collision with a bad hash

We hash five words into 8 buckets using two functions. The sum hash sends the anagrams 'listen', 'silent' and 'enlist' to the same bucket, because addition does not care about order. The polynomial hash spreads them out. Same input, same table size: only the quality of the function changed.

python
def sum_hash(s):
    return sum(map(ord, s))

def poly_hash(s, base=31, mod=10**9 + 7):
    h = 0
    for ch in s:
        h = (h * base + ord(ch)) % mod
    return h

words = ['listen', 'silent', 'enlist', 'cat', 'dog']
print([sum_hash(w) % 8 for w in words])   # first three equal
print([poly_hash(w) % 8 for w in words])  # spread out

Finding a pattern with a rolling hash

Rabin-Karp searches 'abracadabra' for 'cad'. We hash the pattern once, then hash the first window 'abr'. Each step drops the left character, multiplies by the base and adds the next character, so each window costs O(1). When the window hash equals the pattern hash, we compare the actual characters to rule out a false match. The match is at index 4.

python
def rabin_karp(text, pat, B=256, M=1_000_000_007):
    k, n = len(pat), len(text)
    if k > n: return -1
    top = pow(B, k - 1, M)
    hp = ht = 0
    for i in range(k):
        hp = (hp * B + ord(pat[i])) % M
        ht = (ht * B + ord(text[i])) % M
    for i in range(n - k + 1):
        if hp == ht and text[i:i + k] == pat:
            return i
        if i + k < n:
            ht = ((ht - ord(text[i]) * top) * B + ord(text[i + k])) % M
    return -1

print(rabin_karp('abracadabra', 'cad'))  # 4

Quick reference

  • Bucket index = hash(key) % capacity, or hash & (capacity - 1) when capacity is a power of two
  • If a == b then hash(a) == hash(b); the reverse need not hold
  • Hashable: int, float, str, bytes, tuple of hashables, frozenset. Not: list, dict, set
  • Rolling update: h = ((h - left * B^(k-1)) * B + new) % M
  • First collision expected after about sqrt(m) keys (birthday effect)
  • PYTHONHASHSEED=0 disables str hash randomisation for debugging
  • hash(1) == hash(1.0) == hash(True): they are one dict key

Common mistakes

  • Defining __eq__ on a class without a matching __hash__.
  • Assuming equal rolling hashes prove equal strings without verifying.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Which property is required of every hash function used in a hash table?

Question 2

2Why does summing character codes make a poor string hash?

Question 3

3A table has 2^32 possible hash values. Roughly how many random keys give a 50 percent chance of at least one collision?

Question 4

4You define __eq__ on a class but not __hash__. What happens when you put an instance in a set?

Question 5

5What is the cost of sliding a polynomial rolling hash window one position?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Show that a list cannot be a dict key but a tuple can. Then write a function that converts a list of lists into a set of tuples so duplicates are removed. Example: [[1, 2], [1, 2], [3]] gives {(1, 2), (3,)}.

  2. Exercise 2medium

    Write a Point class with x and y where two points with the same coordinates are equal and work as the same set member. Example: len({Point(1, 2), Point(1, 2)}) is 1.

  3. Exercise 3hard

    Write count_distinct_substrings_of_len(s, k) that counts distinct substrings of length k in O(n) expected time using a rolling hash. Example: ('abab', 2) returns 2 ('ab' and 'ba').

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is hash() the same as a cryptographic hash like SHA-256?
No. Python's hash() is built for speed in tables and is randomised per process for strings. For passwords, file checksums or signatures use hashlib (SHA-256) or a password hash like bcrypt or Argon2.
Why does hash('cat') change every time I run Python?
String hashes are seeded with a random key at startup to block hash flooding attacks. Set PYTHONHASHSEED to a fixed number if you need repeatable values.
Can I store hash values in a database to compare later?
Not from Python's hash(), because it differs between runs. Use a stable hash such as hashlib.sha256 or zlib.crc32 instead.

Go deeper

ShareXLinkedInWhatsApp