Sub topic 16
Collision Resolution by Chaining
Assume you know arrays, modular arithmetic, and the basic idea of a hash function. A hash table stores key-value pairs by converting each key into an array index. A collision occurs when two different keys produce the same index.
Chaining resolves collisions by storing a collection of entries at every table slot. The collection is often a linked list, although a dynamic array or balanced tree can also be used.
How chaining works
For a table of size \(m\), a simple hash function is:
\[ h(k) = k \bmod m \]
When inserting key \(k\), compute \(h(k)\) and add the entry to that slot's chain. Searching computes the same index, then checks entries in that chain.
A chain can contain multiple keys. Therefore, the table does not become unusable when several keys map to one slot.
Load factor and running time
The load factor is the average number of entries per slot:
\[ \alpha = \frac{n}{m} \]
Here, \(n\) is the number of stored entries and \(m\) is the number of slots. With a uniform hash function, the expected chain length is approximately \(\alpha\).
| Operation | Expected time | Worst-case time |
|---|---|---|
| Insert | \(\Theta(1)\) | \(\Theta(n)\) |
| Search | \(\Theta(1+\alpha)\) | \(\Theta(n)\) |
| Delete | \(\Theta(1+\alpha)\) | \(\Theta(n)\) |
Expected constant time assumes that keys are distributed roughly evenly. In the worst case, every key hashes to the same slot. The table then behaves like one linear list.
For an unsuccessful search, every entry in the selected chain may be checked. For a successful search, the expected number of checks depends on where the matching entry occurs. If insertion places new entries at the front, insertion is constant time, but recently inserted entries are found more quickly.
Implementation pattern
def insert_chained(table, key, value):
index = key % len(table)
for i, (old_key, _) in enumerate(table[index]):
if old_key == key:
table[index][i] = (key, value)
return
table[index].append((key, value))
table = [[] for _ in range(5)]
insert_chained(table, 12, "A")
insert_chained(table, 7, "B")
print(table)Keys 12 and 7 both map to slot 2, so both entries appear in that chain. Updating an existing key avoids storing duplicate keys.
GATE strategy
When solving a chaining question:
- Compute each key's hash index.
- Group keys that have the same index.
- Count entries in the relevant chain.
- Use \(\alpha=n/m\) for expected-cost questions.
- Check whether the question asks for successful or unsuccessful search.
Exercise
A table has 10 slots and 35 keys distributed uniformly. What is the load factor, and what is the expected unsuccessful-search cost under chaining?
Show answer
The load factor is α = 35/10 = 3.5. The expected cost is Θ(1 + α) = Θ(4.5), which is Θ(1) when the table size and load factor are treated as bounded.