CAP7004 · Unit 4: Hashing
Hash tables and hash functions
8 practice questions
Key points
- Index = hash(key) % size; average O(1) operations
- Load factor = items / slots; resize to keep it low
- Only hashable (immutable) keys allowed in dict/set
- Equal keys must have equal hashes
A hash table stores key-value pairs in an array. A hash function maps a key to an index: index = hash(key) % table_size. If the function is good, lookup, insert and delete take O(1) average time. The worst case is O(n) when many keys land in the same slot.
Good hash functions are fast, deterministic (same key, same hash), and spread keys uniformly. Common methods: division (k % m, choose m prime), multiplication, folding digits, summing character codes for strings. Summing codes is weak because "abc" and "cba" collide.
Load factor = n / m (stored items / slots). Higher load means more collisions; tables resize and rehash (typically growing) when the load passes a threshold. Python's dict resizes automatically.
Python:
- Keys must be hashable: immutable and with a stable hash.
int,str,tupleof hashables work;list,set,dictraiseTypeError: unhashable type. 1,1.0andTruehash equal and are equal, so they are the same key.- String hashes vary between runs (hash randomisation), so never store them as permanent ids.
setis a hash table without values. Counting words:d[w] = d.get(w, 0) + 1, orcollections.Counter.
Exam pitfall: hashing gives no ordering and no efficient range queries.
Try two questions
The average time to look up a key in a hash table is:
- O(n)
- O(1)
- O(n log n)
- O(log n)
Show the answer
B. A good hash function leads straight to the right slot.
In the worst case, a lookup in a hash table takes:
- O(n^2), from repeated rehashing
- O(n), when all keys collide in one slot
- O(1) always, even with collisions
- O(log n) always, even in a bad table
Show the answer
B. If every key lands in one slot, searching it is a linear scan.