Sub topic 10
Why lookups are O(1) on average and O(n) at worst
This chapter assumes you can read Python, know introductory Big-O notation, and have seen separate chaining and load factor. It explains where the average and worst-case costs come from and when each one applies.
The cost of one lookup
A lookup does three things:
- Hash the key.
- Reduce the hash to a bucket index with modulo.
- Search the entries that live in that bucket.
Steps 1 and 2 take constant time for short keys. Step 3 decides the total. Its cost depends on how many entries share the bucket you land in.
Why the average case is O(1)
Suppose the hash function spreads keys evenly across m buckets and the table holds n entries. Each bucket then holds about n / m entries. That ratio is the load factor, written α.
An unsuccessful lookup scans a whole chain, so it costs about 1 + α steps. A successful lookup scans about half a chain on average, so it costs about 1 + α/2.
Resizing keeps α below a fixed limit such as 0.75. Because α is bounded by a constant, the expected cost 1 + α is also bounded by a constant. That is the meaning of O(1) on average. The bound does not depend on n.
The following program counts how long the chains are in the ChainedHashTable design from the previous chapters.
class CountingTable:
def __init__(self, capacity=8, max_load=0.75):
self._buckets = [[] for _ in range(capacity)]
self._size = 0
self._max_load = max_load
def put(self, key, value):
bucket = self._buckets[hash(key) % len(self._buckets)]
for i, (k, _) in enumerate(bucket):
if k == key:
bucket[i] = (key, value)
return
bucket.append((key, value))
self._size += 1
if self._size / len(self._buckets) > self._max_load:
self._resize(len(self._buckets) * 2)
def _resize(self, new_capacity):
old = self._buckets
self._buckets = [[] for _ in range(new_capacity)]
for bucket in old:
for k, v in bucket:
self._buckets[hash(k) % new_capacity].append((k, v))
def longest_chain(self):
return max(len(b) for b in self._buckets)
for n in (1_000, 10_000, 100_000):
t = CountingTable()
for i in range(n):
t.put(i, i)
print(n, t.longest_chain())With integer keys, Python's hash returns the integer itself, so these keys spread evenly and chains stay very short. The longest chain stays small even as n grows by a factor of 100.
Why the worst case is O(n)
The average-case argument assumes the keys spread out. If every key lands in the same bucket, the table behaves like one linked list of n entries, and each lookup scans all of them.
class BadKey:
def __init__(self, value):
self.value = value
def __hash__(self):
return 42
def __eq__(self, other):
return self.value == other.value
for n in (500, 1_000, 2_000):
d = {BadKey(i): i for i in range(n)}
print(n, "entries built")Every BadKey hashes to 42. Building the dictionary takes O(n²) total time, because each insertion has to compare against all earlier entries with the same hash. Doubling n makes the build about four times slower.
Open addressing fails the same way. Colliding keys form long runs of occupied slots, and a probe sequence must walk through the whole run.
Resizing and amortized cost
A resize touches every entry, so a single put that triggers it costs O(n). Because the table doubles each time, resizes become rarer as it grows. Over n insertions the total resize work is about n + n/2 + n/4 + ..., which is less than 2n. Spread across all insertions, that is O(1) per insertion. This is called amortized O(1).
Average and amortized are different ideas:
| Term | What it averages over | What it assumes |
|---|---|---|
| Average case | Possible keys or hash outcomes | A hash function that spreads keys well |
| Amortized | A sequence of operations | Occasional expensive operations, such as resizes, are rare |
When the worst case matters
The worst case can come from three sources:
- A poor hash function, such as one that uses only the first character of a string.
- Keys with structure that interacts badly with the table size, such as multiples of 8 in a table with 8 buckets.
- An attacker who chooses keys that collide on purpose. A later chapter covers this as hash flooding.
Exercise
A chained hash table keeps its load factor at or below 0.75. Roughly how many entries does an unsuccessful lookup compare, and why does that number not grow as the table gets larger?
Show answer
About 1 + 0.75, so fewer than two entries. Resizing keeps the load factor bounded by a constant, so the average chain length stays the same however large n becomes.
Exercise
A table uses a hash function that returns the length of a string key. You insert 10,000 different words. Which cost applies to lookups, and why?
Show answer
Lookups approach O(n). Word lengths span only a few dozen values, so the 10,000 keys fall into a few dozen buckets and the chains grow in proportion to n.