Computer Science · Simulator 058
A hash table turns a key into an array index so lookups are nearly instant. But two keys can land in the same slot. Insert keys one by one, compare collision-resolution strategies, and watch how probe counts climb as the table fills.
CollegeCollege data structures
A hash function maps a key to a slot: h(k) = k mod m for integer keys, or a polynomial string hash. When two keys map to the same slot, that is a collision:
As α approaches 1, open addressing degrades sharply. Tables usually resize (double m and rehash) at α ≈ 0.7. The readout compares measured average probes with these formulas. A poor hash, for example m sharing factors with patterned keys, makes collisions much worse.
Keys are integers or short strings; deletion (which needs tombstones in open addressing) is not shown.
With linear probing, why is inserting into a slot right after a long cluster more likely than into an isolated empty slot?
Any key hashing anywhere into the cluster probes to its end, so a slot right after a cluster of length L is filled with probability about (L + 1)/m, against 1/m for an isolated slot. Clusters therefore grow faster the longer they are: the “rich get richer” effect behind primary clustering.
Table of size m = 11 with h(k) = k mod 11. Insert 22, 13, 35, 44 and 5.
Home slots: 22 → 0, 13 → 2, 35 → 2, 44 → 0, 5 → 5. Two collisions.
Linear probing: 22 goes to 0 and 13 to 2. 35 finds 2 taken and moves to 3. 44 finds 0 taken and moves to 1. 5 goes to 5. Probes: 1, 1, 2, 2, 1, an average of 1.4 to find each key again.
Chaining: slot 0 holds 22 and 44, slot 2 holds 13 and 35 and slot 5 holds 5. The average successful search is also 1.4.
Load factor α = 5 / 11 ≈ 0.45. At this level both methods are fast; linear probing slows sharply above about 0.7. Set m = 11 and type the five keys in.
A structure that turns a key into an array position with a hash function, so lookups, inserts and deletes take about the same short time however many items are stored.
Chaining keeps a small list at each slot for all keys that land there. Open addressing, such as linear or quadratic probing, stores every key in the array itself and searches for the next free slot on a collision.
Keys often share patterns, such as all being even or multiples of 5. With a prime size, k mod m spreads such keys over all slots instead of a few.