Sub topic 10
Why lookups are O(1) on average and O(n) at worst
This chapter assumes you know Big-O notation at an introductory level and have read the earlier chapters on hash functions, chaining, linear probing, and load factor. Here you will see where the constant-time claim comes from, what assumptions it relies on, and how it fails.
What "average" means here
A lookup does three things: hash the key, reduce the hash to a bucket index, and search that bucket. The first two steps take constant time for keys of bounded size. The third step depends on how many entries share the bucket.
So the cost of a lookup is the cost of hashing plus the number of entries you inspect. The "O(1) average" claim says that, under certain assumptions, the number inspected stays bounded by a constant that does not grow with n.
The assumption is simple uniform hashing. Each key is equally likely to land in any bucket, independently of the other keys. Real hash functions only approximate this, so the claim is a model of typical behavior.
Expected chain length under chaining
Let n be the number of stored entries and m the number of buckets. The load factor is α = n / m. Under simple uniform hashing, the expected length of any one chain is α.
- An unsuccessful search (the key is absent) scans one whole chain. Expected entries inspected: α.
- A successful search finds the key partway along its chain. Expected entries inspected: about 1 + α/2.
Both numbers depend on α, not on n. If resizing keeps α at or below 0.75, a search inspects about two entries at most, whether the table holds a thousand keys or a billion.
This is why resizing matters for the complexity claim. Without it, m stays fixed while n grows, α grows with n, and the cost becomes O(n / m), which is linear in n.
Expected probes under linear probing
For open addressing the cost is higher and rises sharply near full. Linear probing creates clusters, which are runs of occupied slots. A key that hashes into a cluster has to walk to its end. Longer clusters catch more new keys, so clusters grow faster than their share of the table.
The classic approximations for linear probing, with load factor α, are:
- Successful search: ½ (1 + 1 / (1 − α)) probes.
- Unsuccessful search: ½ (1 + 1 / (1 − α)²) probes.
| Load factor α | Linear probing, successful | Linear probing, unsuccessful | Chaining, unsuccessful |
|---|---|---|---|
| 0.25 | 1.17 | 1.39 | 0.25 |
| 0.50 | 1.50 | 2.50 | 0.50 |
| 0.75 | 2.50 | 8.50 | 0.75 |
| 0.90 | 5.50 | 50.50 | 0.90 |
The squared term explains why open-addressing tables resize at lower load factors than chained ones. The sample table in this tutorial uses 0.5 for probing and 0.75 for chaining.
Resizing and amortized cost
A single insert that triggers a resize copies every entry, so that one operation costs O(n). Yet inserts are still O(1) on average, because the expensive step is rare.
Suppose the table doubles each time it fills. Starting from capacity 8, the resizes copy about 6, 12, 24, and so on up to n/2 entries. These sum to less than n. Spread over n inserts, the copying adds under one extra move per insert. This is called amortized O(1): the average over a whole sequence of operations, with no probability involved.
Amortized is a different guarantee from expected. Expected cost depends on the hash function behaving well. Amortized cost depends only on the growth policy. A latency-sensitive system can still see one slow insert, even though the average is fine.
Where O(n) comes from
The worst case happens when many keys land in the same bucket. Then a lookup scans a chain of length close to n, or probes a cluster of that length. There are three common causes.
- A poor hash function. One that returns a constant, ignores part of the key, or produces few distinct values sends every key to the same few buckets.
- A bad match between hash and table size. If hash values share a factor with a power-of-two capacity, for example all multiples of 8 in a table of 8 buckets, only some buckets are ever used.
- Adversarial input. An attacker who knows your hash function can choose keys that all collide. This is hash flooding, covered in a later chapter.
Even with a good hash function, chains are not all the same length. With n keys in about n buckets, the longest chain grows slowly, roughly like log n / log log n. The average stays constant but the maximum drifts upward. That is fine in practice, and it shows that O(1) describes the mean, not every lookup.
Seeing both cases
The first program places random hash values into buckets and reports the longest chain at a load factor of 0.75.
import random
from collections import Counter
def longest_chain(n, m, seed=0):
rng = random.Random(seed)
counts = Counter(rng.randrange(m) for _ in range(n))
return max(counts.values())
for n in (1000, 10000, 100000):
m = int(n / 0.75)
print(n, m, longest_chain(n, m))The average chain length is 0.75 in every row. The longest chain is larger and grows slowly as n grows, which matches the theory above.
The second program forces the worst case. BadKey defines equality correctly but returns the same hash for every instance, so every key collides.
import time
class BadKey:
def __init__(self, n):
self.n = n
def __eq__(self, other):
return isinstance(other, BadKey) and self.n == other.n
def __hash__(self):
return 42
def time_lookups(keys):
d = {k: True for k in keys}
start = time.perf_counter()
for k in keys:
d[k]
return time.perf_counter() - start
for n in (500, 1000, 2000):
good = time_lookups([f"k{i}" for i in range(n)])
bad = time_lookups([BadKey(i) for i in range(n)])
print(n, round(good * 1000, 3), round(bad * 1000, 3))The times are in milliseconds and vary by machine. Look at the trend. The string-key column grows roughly in proportion to n, because n lookups each cost O(1). The BadKey column grows roughly fourfold each time n doubles, because each of the n lookups costs O(n), giving O(n²) in total.
Worst-case mitigations in practice
Libraries limit the damage in several ways.
- Resizing keeps α bounded, which handles the case where the table is simply too full.
- Randomized hashing seeds the hash function per process so that attackers cannot predict collisions.
- Treeified buckets replace a long chain with a balanced tree. Java's
HashMapdoes this once a chain passes a threshold, which turns the worst case from O(n) into O(log n) for keys that can be ordered. - Better probing schemes, such as Robin Hood or cuckoo hashing, bound the variance of lookup cost. Cuckoo hashing guarantees at most a fixed number of slot checks per lookup.
None of these removes the worst case in every situation. They raise the cost of reaching it.
Common errors when reasoning about cost
- Treating hash cost as free. Hashing a string of length L costs O(L). For long keys, lookup cost is O(L), not O(1). Python caches string hashes, but the first hash of each string still pays this cost.
- Ignoring the equality check. A hash match is followed by a full key comparison, which also costs O(L).
- Assuming deletes are free. Tombstones count toward the probing load factor. A table full of tombstones behaves like a full table even if few entries are live, until a resize cleans it up.
- Confusing expected and amortized cost. One relies on the hash distribution, the other on the growth policy.
Exercise
A chained hash table with 12 buckets holds 9 keys, and the hash function spreads keys uniformly. (a) What is the load factor and the expected number of entries inspected in an unsuccessful search? (b) A lookup in the same table is slow because all 9 keys landed in one bucket. What is the cost of a lookup for the last key in that chain, and what does this show about the O(1) claim?
Show answer
(a) The load factor is 9 / 12 = 0.75, so an unsuccessful search inspects 0.75 entries on average. (b) The last key in a single chain of 9 requires inspecting all 9 entries, which is O(n). This shows that O(1) is an average under uniform hashing, not a guarantee for every lookup, and that a poor or adversarial hash function can cause the worst case.
Exercise
A table starts at capacity 4 and doubles whenever it becomes full. You insert 16 keys. Count how many entries are copied by resizes in total, and explain why this keeps the amortized cost of insertion at O(1).
Show answer
Resizes happen when the table is full: at 4 entries (copy 4, capacity becomes 8), at 8 entries (copy 8, capacity 16), and at 16 entries only if a 17th insert arrives, so within 16 inserts the copies total 4 + 8 = 12. In general the copies form a geometric sum below n, so the total copying work is less than one move per insert on average. Each resize is expensive but rare, and the cost spread over all inserts is a constant.