Sub topic 1
Hash Functions and What Makes a Good One
Prerequisites
You should know basic programming, arrays, dictionaries or maps, binary and hexadecimal notation, bitwise operations such as XOR, and the modulo operator.
What a Hash Function Does
A hash function maps an input of any size to a fixed-size value called a hash value. The input might be a string, a file, or a data structure. The output is usually an integer represented with a fixed number of bits.
A hash function is deterministic: the same input always produces the same output under the same rules. It is not normally reversible. You cannot reconstruct the original input from its hash value.
def bucket_index(key, bucket_count):
return hash(key) % bucket_count
buckets = [[] for _ in range(8)]
for key in [12, 25, 41]:
buckets[bucket_index(key, len(buckets))].append(key)
print(buckets)Why Hash Tables Need Hash Functions
A hash table stores key-value pairs in an array. The hash function converts a key into an array position, often called a bucket index. This lets the table find a likely location without checking every key.
If the hash function spreads keys well, lookup, insertion, and deletion usually take constant average time, written as O(1). A collision occurs when different keys select the same bucket. The table handles collisions using a method such as a linked chain or an open-addressing probe sequence.
What Makes a Hash Good
For a general-purpose hash table, evaluate these properties:
- Determinism: equal keys must produce equal hash values.
- Uniformity: unrelated keys should spread across buckets instead of clustering.
- Speed: hashing should cost little compared with the table operation.
- Avalanche behavior: a small input change should produce a substantially different hash value. This helps prevent patterns in keys from creating clusters.
Collisions Are Unavoidable
The pigeonhole principle explains why collisions must exist. If a function maps more than 256 possible inputs into 256 output values, at least two inputs share an output. Real hash functions accept vastly more inputs than their fixed-size results can represent.
A collision does not automatically make a hash table incorrect. The table's collision-handling strategy preserves correctness. Too many collisions do reduce performance because operations must inspect more entries.
Exercise
Why can a deterministic hash function still produce collisions?
Show answer
Because its fixed-size output has fewer possible values than its input has possible values. Different inputs must sometimes share one output.