Edexcel International Advanced Level Computer Science, point 18.2.5
A collision happens when two keys hash to the same index (14.1.2). They can't be avoided, so a hash table needs a method to handle them. In Unit 4 you must be able to select, amend and write code for separate chaining, linear probing and rehashing. Check the PLS for details.
The examples use this hash function (sum of character codes mod table size) and keys "Amy" and "Mya", which both hash to 1 with a table size of 7:
def hash_value(key, size):
return sum(ord(ch) for ch in key) % size
a. Separate chaining
Each bucket holds a list (a chain) of all the items that hash to it.
class ChainedTable:
def __init__(self, size=7):
self.size = size
self.buckets = [[] for _ in range(size)]
self.count = 0
def insert(self, key, value):
bucket = self.buckets[hash_value(key, self.size)]
for pair in bucket:
if pair[0] == key:
pair[1] = value
return
# a collision just extends the chain
bucket.append([key, value])
self.count += 1
def find(self, key):
for k, v in self.buckets[hash_value(key, self.size)]:
if k == key:
return v
return None
def remove(self, key):
bucket = self.buckets[hash_value(key, self.size)]
for i, (k, v) in enumerate(bucket):
if k == key:
del bucket[i]
self.count -= 1
return True
return False
- Benefits: never full, simple removal, performance degrades gradually.
- Drawbacks: extra memory for the chains, and long chains slow look-ups ( in the worst case).
b. Linear probing
All items are stored in the table itself. If the slot is taken, try the next slot, then the next, wrapping round, until a free one is found.
class ProbingTable:
def __init__(self, size=7):
self.size = size
# each slot: None or (key, value)
self.slots = [None] * size
self.count = 0
def insert(self, key, value):
if self.count == self.size:
raise OverflowError("table full")
i = hash_value(key, self.size)
while self.slots[i] is not None and self.slots[i][0] != key:
# the next slot, wrapping round
i = (i + 1) % self.size
if self.slots[i] is None:
self.count += 1
self.slots[i] = (key, value)
def find(self, key):
i = hash_value(key, self.size)
for _ in range(self.size):
if self.slots[i] is None:
# an empty slot: the key isn't here
return None
if self.slots[i][0] == key:
return self.slots[i][1]
i = (i + 1) % self.size
return None
Trace (size 7): insert Amy (1), Sam (2), Mya (hashes to 1):
| Step | Hash | Slot checked | Result |
|---|---|---|---|
| Amy | 1 | 1 (empty) | stored at 1 |
| Sam | 2 | 2 (empty) | stored at 2 |
| Mya | 1 | 1 (Amy), 2 (Sam), 3 (empty) | stored at 3 |
Searching for Mya: hash 1: Amy, no; slot 2: Sam, no; slot 3: Mya found (3 probes).
Removing with open addressing
Don't just empty the slot: a later search would stop at the gap and wrongly report that a key further along the probe sequence is missing. Mark the slot as "deleted" (a special value, a tombstone), which find skips over, and which insert may reuse.
- Benefits: no extra structures, good use of memory and cache.
- Drawbacks: clustering (runs of filled slots grow, making probes longer), the table can fill up, and removal needs tombstones.
c. Rehashing
When the load factor gets too high, make a bigger table and re-insert every item (each key's index changes, because it depends on the table size).
def load_factor(self):
return self.count / self.size
def rehash(self):
old = [pair for pair in self.slots if pair is not None]
# a larger size (often odd or prime)
self.size = self.size * 2 + 1
self.slots = [None] * self.size
self.count = 0
for key, value in old:
self.insert(key, value)
def insert_safely(self, key, value):
if self.load_factor() >= 0.7: # a typical limit
self.rehash()
self.insert(key, value)
- Rehash at about 0.7 (for open addressing).
- The cost is for the rehash itself, but it happens rarely, so the average cost of an insert stays low.
- Chaining can also be rehashed (when chains get long).
The three methods compared
| Separate chaining | Linear probing | Rehashing | |
|---|---|---|---|
| Idea | A list per bucket | Use the next free slot | Grow the table and re-insert |
| Table can fill? | No | Yes | Avoids it |
| Extra memory | Chains | None | A bigger table |
| Clustering | No | Yes | Reduces it |
| Removal | Easy | Needs tombstones | n/a |
| Used with | Itself | Itself | Either of the others |
Worked example
Task: insert Amy, Sam, Mya and Zoe into a probing table of size 5, using sum of codes mod 5, rehashing when the load factor reaches 0.7 or more.
Hash values mod 5: Amy = 295 mod 5 = 0, Sam = 289 mod 5 = 4, Mya = 295 mod 5 = 0, Zoe = (90 + 111 + 101 = 302) mod 5 = 2.
| Step | Action | Table (size 5) | Load factor |
|---|---|---|---|
| Insert Amy | slot 0 free | [Amy, -, -, -, -] |
0.2 |
| Insert Sam | slot 4 free | [Amy, -, -, -, Sam] |
0.4 |
| Insert Mya | slot 0 taken, probe slot 1: free | [Amy, Mya, -, -, Sam] |
0.6 |
| Insert Zoe | load factor is 0.6, so no rehash yet; slot 2 free | [Amy, Mya, Zoe, -, Sam] |
0.8 |
The load factor is now 0.8, which is over 0.7, so before the next insert the table is rehashed to size : each key is hashed again mod 11, so its position changes (Amy 295 mod 11 = 9, Mya = 9 (collision, so slot 10), Sam 289 mod 11 = 3, Zoe 302 mod 11 = 5).
New table (size 11): [-, -, -, Sam, -, Zoe, -, -, -, Amy, Mya], load factor .
Exam tip: trace each insert: hash, check the slot, probe forward (wrapping with % size) until you find a free one. For rehashing, recalculate every hash with the new size. Know why open-addressing removal needs a marker. Compare the methods (memory, clustering, full table).
Check yourself
What is a collision?
Two different keys producing the same hash index.
How does separate chaining handle a collision?
Each bucket holds a list, and the colliding item is added to the list in that bucket.
What is clustering in linear probing?
Runs of consecutive filled slots build up, so later keys need more probes to find a free slot.
Why must every item be re-hashed when the table is rehashed?
The index depends on the table size, so each key's position changes in the larger table.
Why can't a slot in a probing table simply be emptied when an item is removed?
A later search would stop at the gap and wrongly conclude that keys further along the probe sequence aren't present, so a deleted marker is used.