Section 14.3

Worst-case versus average-case complexity

Definition

Worst-case complexity is the largest cost that an algorithm §14.1 can incur on any input of a given size nn. Average-case complexity is the expected cost on inputs of size nn 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 nn keys, and a lookup of a key that is not stored compares it with all nn 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.

  1. Fix the input size nn and the set of inputs of that size that the algorithm accepts.

  2. Worst case: take the largest cost over that whole set. Likelihood plays no part; one bad input is enough.

  3. 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.

  4. 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 Θ(n)\Theta(n) for a cost that grows in proportion to nn.

Linear search checks the elements of an array §14.5 of nn elements one by one until it finds the target. In the worst case the target is last or absent: nn comparisons. If the target is present and equally likely to be at each position, a target at position kk, counting from 1, costs kk comparisons, and the average is (1+2+…+n)/n=(n+1)/2(1 + 2 + \dots + n)/n = (n + 1)/2. Both are Θ(n)\Theta(n); 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 (n−1)+(n−2)+…+1=n(n−1)/2(n - 1) + (n - 2) + \dots + 1 = n(n - 1)/2, which is Θ(n2)\Theta(n^2). Averaged over all orderings of nn distinct elements, it makes about 1.39nlog2n1.39\, n \log_2 n comparisons, Θ(nlogn)\Theta(n \log n). A pivot chosen at random gives that expected count for every input.

A hash table can be given each kind of guarantee.

Worked example

A toy table has 4 buckets and the hash function h(k)=kmod4h(k) = k \bmod 4, the remainder when the key kk 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 1+4m1 + 4m, for a whole number mm, lands in the same bucket, so an attacker who knows hh 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 iith insertion compares the new key with the i−1i - 1 keys already there, and the total is 0+1+…+999=999×1000/2=499,5000 + 1 + \dots + 999 = 999 \times 1000 / 2 = 499{,}500 comparisons. Ordinary keys, each landing in a bucket chosen uniformly at random and independently of the others, behave differently: the iith insertion finds on average (i−1)/1024(i - 1)/1024 earlier keys in its bucket, and the expected total is 499,500/1024≈488499{,}500 / 1024 \approx 488 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 0.9×1+0.1×10=0.9+1.0=1.90.9 \times 1 + 0.1 \times 10 = 0.9 + 1.0 = 1.9 steps; the worst case is 10 steps. An attacker who can force the expensive case every time makes every operation cost 10 steps, 10/1.9≈5.310 / 1.9 \approx 5.3 times the average.

Stated precisely

Let InI_n be the set of accepted inputs of size nn, and let T(x)T(x) be the cost on input xx. The worst-case cost is W(n)=maxx∈InT(x).W(n) = \max_{x \in I_n} T(x). Let DD be a probability distribution that gives each input x∈Inx \in I_n a probability D(x)D(x), the probabilities summing to 1. The average-case cost under DD is AD(n)=∑x∈InD(x)T(x).A_D(n) = \sum_{x \in I_n} D(x)\, T(x). A weighted average whose weights sum to 1 never exceeds the largest value averaged, so AD(n)≤W(n)A_D(n) \le W(n) for every DD.

For a randomized algorithm, let T(x,r)T(x, r) be the cost on input xx when the algorithm’s random choices are rr, and let Er[⋅]E_r[\cdot] be the expected value over those choices. The expected worst-case cost is R(n)=maxx∈InEr[T(x,r)].R(n) = \max_{x \in I_n} E_r[T(x, r)]. It holds for every input on one assumption: the input is fixed independently of rr, so whoever chooses xx neither sees nor predicts rr.

For hash tables this guarantee has a standard form. A family of hash functions into mm buckets is universal when, for any two different keys xx and yy, a function chosen uniformly at random from the family maps xx and yy to the same bucket with probability at most 1/m1/m. J. Lawrence Carter and Mark Wegman introduced universal hashing in the late 1970s [244]. With one list per bucket and nn stored keys, the expected number of stored keys other than xx in the bucket of any key xx is then at most n/mn/m, 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 h(k)=kmod4h(k) = k \bmod 4, the remainder after division by 4, the keys 1, 5, 9, 13 and every other key of the form 1+4m1 + 4m collide. Inserting nn such keys, each with a duplicate check, costs n(n−1)/2n(n - 1)/2 comparisons; keys spread at random over at least nn buckets would cost fewer than n/2n/2 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 O(logn)O(\log n) comparisons, at most a constant times logn\log n, 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].