Sub topic 17
Hash Tables: Keys, Slots, and Collisions
This chapter assumes you know arrays and indexing, modular arithmetic, and the asymptotic notation from earlier chapters. It builds the working model of a hash table. Later chapters cover hash function design, chaining, open addressing, and load factor analysis in detail.
The Idea
A hash table stores keys so that insert, search, and delete take O(1) expected time. It does this by turning a key into an array index.
- A key is the value you look up, such as an integer ID or a string.
- A slot is one position in the underlying array. The array has m slots, numbered 0 to m - 1.
- A hash function h maps a key to a slot number: h(k) is in {0, ..., m - 1}.
Direct addressing is the simple case. If keys are integers in 0..U-1, you can use an array of size U and store key k at index k. This is O(1) but wastes memory when U is huge and only n keys are stored. A hash table uses a smaller array of size m and lets h compress the key universe into m slots.
Why Collisions Are Unavoidable
If the universe of keys has more than m values, then by the pigeonhole principle some two keys must share a slot. A collision happens when two different keys k1 and k2 have h(k1) = h(k2). Even with few keys, collisions are common. With 23 random keys and 365 slots, a collision is more likely than not (the birthday paradox). So every hash table needs a collision resolution strategy.
The Load Factor
The load factor is α = n / m, where n is the number of stored keys and m is the number of slots. It measures how full the table is. Nearly every cost formula in this topic is written in terms of α. With chaining, α can exceed 1. With open addressing, each slot holds at most one key, so α ≤ 1.
A Worked Example
Use m = 5 and h(k) = k mod 5. Insert 12, 25, 37, 44 in that order.
| Key | h(k) = k mod 5 | Result |
|---|---|---|
| 12 | 2 | Slot 2 is empty, so 12 goes there. |
| 25 | 0 | Slot 0 is empty, so 25 goes there. |
| 37 | 2 | Collision with 12. A strategy is needed. |
| 44 | 4 | Slot 4 is empty, so 44 goes there. |
Here n = 4 and m = 5, so α = 0.8. The two main strategies handle key 37 differently.
- Chaining keeps a linked list in each slot. Slot 2 becomes the list 12 → 37 (or 37 → 12, depending on where you insert). The table never fills up.
- Open addressing keeps every key inside the array. When slot 2 is taken, it probes other slots by a fixed rule. With linear probing, it tries slot 3, which is empty, so 37 goes there.
Implementing Both Strategies
The following code builds a small table with each strategy. It runs as shown.
class ChainedTable:
def __init__(self, m):
self.m = m
self.slots = [[] for _ in range(m)]
def insert(self, key):
bucket = self.slots[key % self.m]
if key not in bucket:
bucket.append(key)
def search(self, key):
return key in self.slots[key % self.m]
def delete(self, key):
bucket = self.slots[key % self.m]
if key in bucket:
bucket.remove(key)
class LinearProbeTable:
def __init__(self, m):
self.m = m
self.slots = [None] * m
def insert(self, key):
for i in range(self.m):
slot = (key % self.m + i) % self.m
if self.slots[slot] is None:
self.slots[slot] = key
return slot
raise OverflowError("table full")
def search(self, key):
for i in range(self.m):
slot = (key % self.m + i) % self.m
if self.slots[slot] is None:
return -1
if self.slots[slot] == key:
return slot
return -1
keys = [12, 25, 37, 44]
chain = ChainedTable(5)
for k in keys:
chain.insert(k)
print(chain.slots)
probe = LinearProbeTable(5)
for k in keys:
probe.insert(k)
print(probe.slots)
print(probe.search(37))The output is:
[[25], [], [12, 37], [], [44]]
[25, None, 12, 37, 44]
3Cost Model
A hash table's cost depends on how many keys share a slot or a probe path.
| Case | Cost of search | Reason |
|---|---|---|
| Best | O(1) | The key is the first item examined. |
| Expected (good h, moderate α) | O(1 + α) with chaining | The average chain has length α. |
| Worst | O(n) | All keys hash to the same slot, so the table acts like a list. |
The "simple uniform hashing" assumption says each key is equally likely to land in any slot, independent of other keys. The O(1 + α) result holds under this assumption. It is a property of the hash function and the data together, not of the data structure alone.
Common Errors
- Treating O(1) as a worst-case guarantee. It is an expected cost. A bad hash function, or adversarial keys, can give O(n).
- Forgetting that α can exceed 1 only with chaining. In open addressing, n cannot exceed m.
- Using a hash function that ignores structure in the keys. With h(k) = k mod 10 and keys that all end in 0, every key lands in slot 0.
- Stopping a search at a deleted slot in open addressing. If delete just empties a slot, later searches stop early and miss keys that were placed beyond it. Real implementations mark deleted slots with a tombstone and keep probing past them.
- Assuming hash tables keep keys in order. They do not. Range queries and "next larger key" are not supported efficiently.
Where This Fits
Under chaining, the cost of search is the cost of computing h(k) plus the length of one list. Under open addressing, it is the number of probes until the key or an empty slot is found. The next chapters study how to choose h, how each strategy behaves, and how α turns into expected probe counts.
Exercise
A hash table has m = 7 slots and uses h(k) = k mod 7 with linear probing. Keys 15, 22, 8, 29 are inserted in that order. Which slot does each key occupy, and what is the load factor afterwards?
Show answer
15 mod 7 = 1, so 15 goes to slot 1. 22 mod 7 = 1, which is taken, so it probes slot 2 and lands there. 8 mod 7 = 1, so it probes slots 1 and 2 (taken) and lands in slot 3. 29 mod 7 = 1, so it probes slots 1, 2, 3 (taken) and lands in slot 4. The load factor is 4/7, about 0.57.
Exercise
Why must every hash table handle collisions, even when the number of stored keys is much smaller than the number of slots?
Show answer
The key universe is far larger than m, so by the pigeonhole principle some keys share a slot. Even for a small n, random keys collide with notable probability (the birthday paradox), so a resolution strategy such as chaining or open addressing is always needed.
Exercise
A table using chaining has n = 50 keys and m = 20 slots. Under simple uniform hashing, what is the load factor and the expected cost of an unsuccessful search in terms of list items examined?
Show answer
α = 50 / 20 = 2.5. Under simple uniform hashing, an unsuccessful search examines the whole chain in one slot, which has expected length α = 2.5 items, plus the constant cost of computing h(k). The total is Θ(1 + α).