Definition
Worst-case complexity is the largest cost that an algorithm §14.1 can incur on any input of a given size . Average-case complexity is the expected cost on inputs of size drawn from a stated probability distribution: the cost of each input multiplied by its probability, then summed. The difference that matters is who chooses the input. A worst-case bound holds for every input, including one chosen by an attacker. An average-case bound holds only when the inputs really follow the stated distribution.
The idea
A hash table §14.7 stores keys in buckets. A hash function, a function that computes a number from a key, chooses the bucket, and each bucket holds a list of the keys that landed in it. When keys spread evenly, every list is short, and a lookup compares the sought key with only one or two stored keys. But if every key lands in the same bucket, that list holds all keys, and a lookup of a key that is not stored compares it with all of them.
Ordinary users almost never cause that pile-up. An attacker who knows the hash function can cause it on purpose, by computing in advance many keys with the same hash value; the average over ordinary keys then says nothing about what the attacker sends. In 2003 Scott Crosby and Dan Wallach showed denial-of-service §1.28 attacks that sent such worst-case inputs to the hash tables of real programs [241]. In 2011 Alexander Klink and Julian Wälde showed that, on many popular web platforms, a single request carrying many colliding parameter names could tie up a server’s processor [242].
The useful picture is a game about who chooses the input. Average-case analysis assumes that chance chooses it; worst-case analysis assumes that an opponent chooses it after reading the algorithm. Between the two, the algorithm can make random choices of its own, such as picking its hash function at random when it starts, so that even an opponent who has read the algorithm cannot tell which inputs will be slow.
How it works
Fix a cost measure, such as the number of comparisons, then ask who chooses what.
Fix the input size and the set of inputs of that size that the algorithm accepts.
Worst case: take the largest cost over that whole set. Likelihood plays no part; one bad input is enough.
Average case: state a probability distribution over the set, that is, a probability for each input, the probabilities summing to 1. Multiply each input’s cost by its probability and add the results. The answer is only as true as the distribution.
Randomized algorithm: if the algorithm makes random choices of its own, compute for each input the expected cost over those choices, then take the largest over all inputs. This expected worst-case bound holds for every input, whoever chooses it, provided the input is chosen without knowledge of the algorithm’s random choices.
All three are usually stated in asymptotic notation §14.2, such as for a cost that grows in proportion to .
Linear search checks the elements of an array §14.5 of elements one by one until it finds the target. In the worst case the target is last or absent: comparisons. If the target is present and equally likely to be at each position, a target at position , counting from 1, costs comparisons, and the average is . Both are ; the cases differ only in a constant.
In quicksort the cases differ in growth. Quicksort, a sorting method, picks one element as the pivot, splits the other elements into those smaller and those larger than it, and sorts each part the same way. If the first element is always the pivot, an already sorted input makes every split as uneven as possible, and the comparisons number , which is . Averaged over all orderings of distinct elements, it makes about comparisons, . A pivot chosen at random gives that expected count for every input.
A hash table can be given each kind of guarantee.
Keyed hashing gives an expected bound for every input. The bucket comes from a function that depends on a secret random key chosen when the program starts, so an attacker without the key cannot compute colliding keys in advance. SipHash, published by Jean-Philippe Aumasson and Daniel J. Bernstein in 2012 [243], is a fast keyed function designed for this use, meant to be a pseudorandom function §15.1 (one whose outputs look random to anyone without the key). Python §12.23 uses a SipHash variant to hash strings, and the standard hash map of Rust uses one by default.
A worst-case-bounded structure stores each long bucket as a balanced search tree §14.10 (a sorted tree whose height stays proportional to the logarithm of its size), so even a bucket of all keys costs comparisons per lookup, provided the keys can be put in order. Since Java 8, the
HashMapclass of the Java standard library does this.An explicit limit, such as at most 1000 keys per request, bounds the worst case by the limit itself.
Worked example
A toy table has 4 buckets and the hash function , the remainder when the key is divided by 4. The keys 1, 5, 9 and 13 all leave the remainder 1, so all four land in bucket 1. A lookup of the key 17, which is not stored but also leaves the remainder 1, compares it with all 4 stored keys before it reports “not found”. Every key of the form , for a whole number , lands in the same bucket, so an attacker who knows has an endless supply of colliding keys.
Scale the attack up. An attacker sends 1000 keys that all land in one bucket of a table with 1024 buckets. If each insertion first checks the bucket for a duplicate, the th insertion compares the new key with the keys already there, and the total is comparisons. Ordinary keys, each landing in a bucket chosen uniformly at random and independently of the others, behave differently: the th insertion finds on average earlier keys in its bucket, and the expected total is comparisons. The attack multiplies the work by 1024, the number of buckets.
A two-case model shows the gap between the two bounds. Suppose that under the expected workload an operation costs 1 step with probability 0.9 and 10 steps with probability 0.1. The average is steps; the worst case is 10 steps. An attacker who can force the expensive case every time makes every operation cost 10 steps, times the average.
Stated precisely
Let be the set of accepted inputs of size , and let be the cost on input . The worst-case cost is Let be a probability distribution that gives each input a probability , the probabilities summing to 1. The average-case cost under is A weighted average whose weights sum to 1 never exceeds the largest value averaged, so for every .
For a randomized algorithm, let be the cost on input when the algorithm’s random choices are , and let be the expected value over those choices. The expected worst-case cost is It holds for every input on one assumption: the input is fixed independently of , so whoever chooses neither sees nor predicts .
For hash tables this guarantee has a standard form. A family of hash functions into buckets is universal when, for any two different keys and , a function chosen uniformly at random from the family maps and to the same bucket with probability at most . J. Lawrence Carter and Mark Wegman introduced universal hashing in the late 1970s [244]. With one list per bucket and stored keys, the expected number of stored keys other than in the bucket of any key is then at most , the load factor §14.9, for every set of keys chosen without knowledge of the chosen function.
Limits and common mistakes
An average-case bound needs a probability model. A benchmark that never hit the slow case is not one: it shows what its own inputs did, not what inputs chosen to be slow will do.
Average-case analysis gives no protection against an attacker. For inputs from an untrusted source, the defensible claim is a worst-case bound, or an expected bound for a randomized algorithm whose random choices the attacker cannot see. Sending worst-case inputs on purpose is an algorithmic complexity attack §15.35.
A randomized defense holds only while its randomness stays hidden. If the secret key of a keyed hash leaks, for example through an error message, the order in which the table lists its keys, or the time each lookup takes, the attacker can compute collisions again. A random starting value is not enough on its own either: in 2012 Aumasson, Bernstein and Martin Boßlet showed collisions for MurmurHash, a fast hash function not designed to resist attackers, that held whatever random starting value was chosen [245].
An expected bound does not bound every run. A randomized algorithm can still be slow on a particular run. A system with a deadline needs a bound on the bad runs as well, such as the probability that a run exceeds a given cost.
Worst-case complexity counts steps, not time. It is not a worst-case execution time §9.33, the longest time that a piece of code can take on a particular processor, which also depends on caches, interrupts §6.11 and the rest of the hardware.
The set of accepted inputs is part of the claim. A rule that rejects inputs, such as a limit of 64 keys per request, legitimately lowers the worst case. Never having observed a slow input is not such a rule.
Questions answered
Can an attacker deliberately choose the worst hash-table inputs?
Yes: an attacker who controls the keys and knows or can learn the hash function can choose many keys that land in the same bucket, so that every operation on that bucket compares against every key in it. A hash table stores keys in buckets chosen by a hash function, which computes a number from each key, and its fast lookup is an average-case result that assumes keys spread evenly. With a public function such as , the remainder after division by 4, the keys 1, 5, 9, 13 and every other key of the form collide. Inserting such keys, each with a duplicate check, costs comparisons; keys spread at random over at least buckets would cost fewer than on average. Attacks of this kind have tied up real web servers with a single request.
Three defenses give three different guarantees. A keyed hash function, such as SipHash with a secret random key chosen when the program starts, stops the attacker from computing collisions in advance; its expected bound lasts only while the key stays secret. Storing long buckets as balanced search trees bounds every lookup at comparisons, at most a constant times , whatever the keys, provided the keys can be put in order. A cap on the number of keys per request bounds the total work directly.
Related entries: Hash table (§14.7), Load factor (§14.9), Denial of service (DoS) (§1.28), Algorithmic complexity attack (§15.35), Balanced search tree (§14.10), Asymptotic complexity (§14.2). Further reading: [241, 242, 243, 244, 245].