Sub topic 1
Hash tables and hash functions in brief
Prerequisites
This chapter assumes you know the following:
- Arrays and indexing, including constant-time access by position.
- Basic Python syntax: lists, tuples, and classes.
- Big-O notation, and the difference between average and worst-case cost.
- Modulo arithmetic, such as
17 % 7 == 3.
What a hash table does
A hash table is a data structure that maps keys to values. You give it a key, and it finds the matching value without scanning every entry. Python's dict and set are hash tables.
The idea is to turn a key into an array position. The table keeps an array of slots, and a hash function picks the slot for each key. If the function is cheap, lookup costs a single computation plus one array access. That is why the average cost of put, get, and remove is O(1).
Hash functions
A hash function takes a key and returns an integer, called the hash code. The table then reduces that integer to a valid slot index:
capacity = 8
key = "apple"
index = hash(key) % capacity
print(0 <= index < capacity)Here hash(key) can be any integer, and % capacity maps it into the range 0 to capacity - 1. The result is the key's home slot.
A good hash function has these properties:
- It is deterministic. The same key always gives the same hash code during one run of the program.
- It is fast to compute.
- It spreads keys evenly, so they do not pile up in a few slots.
- Equal keys give equal hash codes. If
a == b, thenhash(a) == hash(b).
The last property is what lets a lookup find the slot where the key was stored.
Python randomizes string hashes between runs. If you print hash("apple") twice in separate runs, you will probably see different numbers. The value is stable only within one process, so never store Python hash codes on disk or depend on their exact values.
How the pieces fit together
A first, naive table
The simplest possible table stores one entry per slot and ignores the possibility that two keys land in the same slot. The code below is a minimal version:
class NaiveHashMap:
def __init__(self, capacity=8):
self._slots = [None] * capacity
def _index(self, key):
return hash(key) % len(self._slots)
def put(self, key, value):
self._slots[self._index(key)] = (key, value)
def get(self, key, default=None):
entry = self._slots[self._index(key)]
if entry is not None and entry[0] == key:
return entry[1]
return default
table = NaiveHashMap()
table.put(1, "one")
table.put(9, "nine")
print(table.get(1))
print(table.get(9))Integers hash to themselves in Python, and 1 % 8 and 9 % 8 are both 1. The key 9 overwrites the entry for 1. The first print shows None, so the value for key 1 is lost without any error.
This situation is called a collision. It happens whenever two different keys have the same slot index. The next chapter explains why collisions cannot be avoided. The remaining chapters cover the two standard fixes: separate chaining, which keeps a collection of entries in each slot, and open addressing, which looks for another free slot in the array.
Key points
- A hash table maps a key to an array slot using a hash function and modulo arithmetic.
- Equal keys must produce equal hash codes.
- Average cost per operation is O(1) only if keys spread out and collisions are handled.
- A table that ignores collisions loses data.
Exercise
A table has capacity 10 and stores integer keys using key % 10 as the slot. Which of the keys 5, 15, and 26 share a slot, and what happens to them in NaiveHashMap if they are inserted in that order?
Show answer
Keys 5 and 15 both map to slot 5, while 26 maps to slot 6. Inserting 15 overwrites the entry for 5, so get(5) returns the default value (None). Key 26 is stored normally.
Exercise
Why must two equal keys always have equal hash codes?
Show answer
A key is stored in the slot computed from its hash code. A later lookup with an equal key computes a slot from its own hash code. If the codes differed, the lookup would probably go to a different slot and miss the stored entry.