Edexcel International Advanced Level Computer Science, point 14.1.2
Definition
A hash table is a data structure that stores key-value pairs and finds items very quickly, using a hash function to calculate where each item is stored from its key. Python's dictionary and set are built on hash tables.
Function and why needed
Searching a list takes time and a binary search (and needs sorted data). A hash table gives an average time of for insert, search and delete, however many items, which is ideal for look-ups (names to phone numbers, words to meanings, symbol tables in compilers, caches).
a. Structure
A hash table is an array of "buckets" (slots), each of which can hold an item (or a list of items).
The hash function
A hash function turns a key into an index. A good hash function:
- Is deterministic: the same key always gives the same index.
- Is fast to calculate.
- Spreads keys evenly across the table, so there are few collisions.
- Always gives a valid index (0 to size - 1).
A simple example (for text keys): add the character codes, then take the remainder after dividing by the table size.
def hash_key(key, size):
total = 0
for ch in key:
total = total + ord(ch)
return total % size
print(hash_key("Amy", 7)) # (65 + 109 + 121) % 7 = 295 % 7 = 1
print(hash_key("Raj", 7)) # (82 + 97 + 106) % 7 = 285 % 7 = 5
print(hash_key("Sam", 7)) # (83 + 97 + 109) % 7 = 289 % 7 = 2
A better function uses position weights (so that "abc" and "cba" differ) and a prime table size.
b. Ways to represent a hash table
Using classes
class HashTable:
def __init__(self, size=7):
self.size = size
self.slots = [None] * size # an array of buckets
self.count = 0
Using references (chaining)
Each bucket holds a reference to the head of a linked list (14.1.1) of the items that hashed there:
class HashTable:
def __init__(self, size=7):
self.buckets = [[] for _ in range(size)] # a list per bucket
self.size = size
self.count = 0
c. Operations
Calculate hash values
Apply the hash function to the key to find its index: index = hash_key(key, size).
Insert
- Calculate the index from the key.
- Store the item at that slot.
- If the slot is already taken (a collision), use a collision method.
Search
- Calculate the index from the key (the same function).
- Look in that slot. If it holds the key, it is found. If not (and the slot is empty), it isn't in the table.
- If there was a collision method, follow the same steps (check the chain, or probe on).
Delete
Find the item and remove it. (With open addressing, mark the slot as "deleted" instead of emptying it, so later searches still probe past it.)
Traverse
Visit every slot (and every item in each chain). The order isn't the insertion order or sorted order.
Handling collisions
A collision happens when two different keys give the same index. Because there are more possible keys than slots, collisions can't be avoided, only handled.
Chaining (separate chaining)
Each slot holds a list (linked list) of all items that hash to it.
- Benefits: never "full", simple deletion, degrades gradually.
- Drawbacks: extra memory for pointers, long chains slow searching to in the worst case.
Open addressing: linear probing
Look for the next free slot: index + 1, index + 2, ... (wrapping round).
def insert_probe(slots, key):
size = len(slots)
i = hash_key(key, size)
for _ in range(size):
if slots[i] is None or slots[i] == key:
slots[i] = key
return i
# move to the next slot, wrapping round
i = (i + 1) % size
raise OverflowError("table full")
- Benefits: no extra structures, good cache use.
- Drawbacks: clustering (groups of filled slots build up, making probing longer), the table can become full, and deletion is tricky.
Other methods: quadratic probing (steps of 1, 4, 9...), double hashing (a second hash function sets the step), rehashing (below).
Load factor and rehashing
The load factor is how full the table is:
- A low load factor (for example 0.3) means few collisions, but wasted memory.
- A high load factor (above about 0.7) means many collisions, and slower operations. With open addressing it can't exceed 1 (the table is full).
Rehashing is creating a larger table (often double the size, or the next prime) and recomputing the hash of every item for the new size, then inserting them again (the old positions are no longer valid, since the index depends on the table size). It is done when the load factor passes a limit.
def rehash(old_slots):
new_size = len(old_slots) * 2 + 1
new_slots = [None] * new_size
for key in old_slots:
if key is not None:
insert_probe(new_slots, key)
return new_slots
- Cost: for the rehash itself, but it happens rarely, so the average insert is still .
Hash table compared with other structures
| Hash table | Sorted array (binary search) | Linked list | |
|---|---|---|---|
| Search | average, worst | ||
| Insert | average | (shifting) | at the front |
| Ordered? | No | Yes | By insertion |
| Memory | Spare slots | Compact | Pointers |
Benefits
- Very fast average search, insert and delete.
- Speed doesn't depend much on the number of items.
- Flexible keys (strings, numbers).
Drawbacks
- Collisions need handling, and worst-case time is .
- Items aren't stored in order, so sorted output or range searches are hard.
- Wasted memory (spare slots), and rehashing is costly.
- Performance depends on a good hash function.
Worked example
Task: a hash table of size 7 uses the hash function sum of character codes mod 7 with linear probing. Insert "Amy", "Sam", "Mya" (in that order) and give the final table and the load factor.
"Amy": , . Slot 1 free: store at 1."Sam": , . Slot 2 free: store at 2."Mya": , . Slot 1 is taken by Amy (collision), so probe slot 2: taken by Sam, then slot 3: free, store at 3.
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| Key | Amy | Sam | Mya |
Load factor .
Searching for "Mya": hash gives 1: not Amy, not Sam, found at 3 (3 probes). Notice how an anagram gave the same hash: this is a weakness of this simple function.
Exam tip: calculate hash values carefully with character codes and mod. For collisions, name a method (chaining or linear probing) and show where the item ends up. Define the load factor and say why rehashing is needed (too many collisions). A good hash function spreads keys evenly.
Check yourself
What does a hash function do?
It converts a key into an index in the table, so the item can be stored and found directly.
What is a collision, and give one way of handling it?
When two different keys give the same index. It can be handled by chaining (a list in each slot) or by probing for the next free slot.
What is the load factor of a table of 20 slots holding 14 items?
14 / 20 = 0.7.
Why is rehashing needed, and why must all items be rehashed?
A high load factor causes many collisions, so the table is enlarged; every item must be rehashed because the index depends on the table size.
What is the average time to search a hash table?
O(1), constant time.