Algorithms Concept

Average and Worst-Case Hash Table Lookups

A hash lookup is O(1) on average when the hash spreads keys evenly and the load factor stays bounded, but the bound is expected rather than worst-case. Collisions concentrated in one bucket, from a weak hash or adversarial keys, degrade a lookup to O(n).

The short answer

A hash table lookup is O(1) on average because the hash function maps a key to a bucket directly, and with a good hash and a bounded load factor each bucket holds O(1) entries. The bound is expected, not worst-case. If many keys land in the same bucket, a lookup scans that bucket and costs O(n); adversarial keys, a weak hash, or an overloaded table can all produce that behavior.

A minimal example

table = {}
for i in range(100_000):
    table[i] = i * 2      # amortized O(1) per insertion
print(table[99_999])      # expected O(1)

C++ exposes the load factor, which is the ratio of elements to buckets:

#include <unordered_map>
#include <string>

std::unordered_map<std::string, int> counts;
counts.max_load_factor(0.7f);
counts.reserve(1000);     // size the table before bulk insertion
for (const auto& word : words) ++counts[word];

Why this happens

With separate chaining, each bucket is a list and the expected chain length is the load factor alpha = n / m. Under uniform hashing, a successful lookup examines about 1 + alpha/2 entries. With open addressing, all entries live in the table itself and the expected number of probes for a successful lookup is about 1/(1 - alpha), which grows sharply as alpha approaches 1. That is why implementations resize: doubling the bucket array and rehashing keeps alpha bounded, and the cost is amortized over the insertions.

The worst case comes from collisions, not from the table size. If every key hashes to the same bucket, chaining degenerates to a linked-list scan of n entries, and open addressing probes the whole table. A hash function that ignores part of the key, or keys chosen to collide, produce exactly that.

Where implementations differ

Table Collision handling Worst-case lookup Note
Python dict Open addressing O(n) Resizes near two-thirds full
Java HashMap Chaining, tree bins O(log n) per bin Bins treeify at eight entries
C++ std::unordered_map Chaining O(n) Bucket count is implementation-defined
Go map Buckets of eight O(n) Randomized hash seed

Java's treeification is the notable exception to the O(n) worst case: when a bin grows past a threshold, it becomes a red-black tree, so a lookup within that bin is O(log n). Python randomizes string and bytes hashes, and Go randomizes map hashing, which makes collision attacks harder; this changes the constant and the attack surface but not the asymptotic worst case.

What changes the answer

Hash quality dominates. Python integer hashes are the integer itself, with -1 mapped to -2 and large values reduced modulo 2**61 - 1; a table that masks a hash with a power of two uses its low bits, so a weak hash that ignores part of the key can still cluster. Strings require hashing every byte, so a lookup on a long key is O(L) in the key length before the table probe, even though the probe itself is constant.

The equality contract matters as much as the hash. Equal keys must have equal hashes; if a key's hash changes after insertion, as with a mutable object used as a key, the entry becomes unreachable. Most languages prevent this by requiring hashable or immutable key types.

Load factor and resizing determine tail latency. Automatic growth is amortized O(1), but an individual insertion that triggers a resize is O(n). Latency-sensitive systems preallocate with reserve or an initial capacity, or use incremental rehashing.

Practical checks

Benchmark with realistic keys rather than integers; hash computation and cache behavior usually dominate real workloads. Reserve capacity when the final size is known. Do not rely on iteration order unless the language guarantees it, and do not use a hash table when you need sorted traversal. If worst-case latency is a requirement, a balanced tree gives O(log n) deterministically, while a hash table gives O(1) expected with an O(n) tail.

Related structures appear throughout graph code: BFS keeps its visited set in a hash set, so its O(V + E) bound assumes these average-case properties; see the queue in breadth-first search.

Sources

Revision history

Published
Updated
— Initial publication.