Sub topic 10
Why Operations Are O(1) on Average, and When They Are Not
This chapter assumes you know basic Big-O notation, can read Python, and have seen how a hash table uses a hash function, buckets and collision handling. Here we connect those pieces to the cost of each operation.
The average-case argument
A lookup in a hash table has three steps:
- Compute
hash(key). For a short string or an integer this takes a fixed amount of work. - Map the hash to a bucket index, usually with
hash(key) % bucket_count. This is one arithmetic step. - Scan the bucket, comparing keys with
==, until you find a match or run out of entries.
Steps 1 and 2 do not depend on how many items the table holds. Step 3 depends on the bucket length. If the hash function spreads keys evenly and the table resizes to keep its load factor bounded, the average bucket holds a small constant number of entries. Say the load factor stays under 1. Then a bucket scan inspects about one entry on average, and the whole operation is O(1).
The O(1) claim therefore rests on two conditions: keys spread evenly, and the table keeps buckets short by resizing.
Where the cost goes
Only the scan step can grow with the data. Everything else stays fixed.
When operations are not O(1)
Many keys in one bucket
If every key lands in the same bucket, the table behaves like a linked list or an array. Each lookup scans all n entries, so the cost is O(n). The next example forces this with a bad hash function.
import time
class BadKey:
def __init__(self, n):
self.n = n
def __hash__(self):
return 1 # every key collides
def __eq__(self, other):
return self.n == other.n
def build(size):
return {BadKey(i): i for i in range(size)}
for size in (500, 1000, 2000):
start = time.perf_counter()
build(size)
print(size, round(time.perf_counter() - start, 4))Doubling size roughly quadruples the time. Each insert scans a growing collision chain, so n inserts cost O(n²) in total.
Expensive hashing or equality
Hashing a string reads every character, so the cost is O(k) for a key of length k. Hashing a tuple hashes each element. When keys are long, "O(1)" really means O(1) in the number of entries, not in the size of the key. Python caches a string's hash after the first computation, which hides the cost on repeated lookups.
Resizing
Most inserts are cheap, but an insert that pushes the load factor past its limit triggers a resize. Resizing allocates a larger array and reinserts every entry, which costs O(n). Because the table grows by a constant factor (often doubling), the resize cost spreads out over many inserts. The result is amortized O(1) per insert, with occasional slow ones. If you need a strict latency bound on every operation, one resize pause can matter.
Adversarial input
An attacker who knows your hash function can craft keys that all collide. That recreates the worst case above. A later chapter covers this as hash flooding.
Summary of costs
| Operation | Average | Worst case | Main cause of worst case |
|---|---|---|---|
| Lookup | O(1) | O(n) | Many keys in one bucket |
| Insert | O(1) amortized | O(n) | Resize, or a long collision chain |
| Delete | O(1) | O(n) | Long collision chain |
| Iterate all | O(n) | O(n) | Visits every entry once |
Exercise
A hash map holds 1,000,000 entries and keeps its load factor below 1. A profiler shows that lookups for one particular group of keys are very slow, while lookups for all other keys are fast. Name one likely cause and one way to check it.
Show answer
The slow keys probably collide, so they sit in long buckets. This can happen because their hash function maps them to the same few values, for example a custom __hash__ that uses only part of the key. To check, compute hash(key) for a sample of the slow keys and count how many distinct values (or distinct values modulo the bucket count) appear. Few distinct values confirm the collision problem. Fix it by making __hash__ use all the fields that __eq__ compares.