Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

Lower Bounds by Adversary Arguments

Proving no algorithm can do better: maximum and minimum, the second largest, and information.

Finding the largest of nn numbers takes n−1n - 1 comparisons, and no cleverness saves a single one. Finding the largest and the smallest takes not 2n−32n - 3 but exactly ⌈3n/2⌉−2\lceil 3n/2 \rceil - 2, and that is optimal too. Bounds like these are statements about every possible algorithm, and they are proved by imagining an opponent who answers your questions as unhelpfully as the rules allow.

What you’ll learn

  • Define the comparison model and adversary arguments, and prove that finding the maximum needs n−1n - 1 comparisons.
  • Prove the exact bound ⌈3n/2⌉−2\lceil 3n/2 \rceil - 2 for the maximum and minimum with an information-counting adversary, and match it with an algorithm.
  • Prove that the second largest needs n+⌈log⁡2n⌉−2n + \lceil \log_2 n \rceil - 2 comparisons, and match it with a tournament.
  • Prove lower bounds for searching, merging and graph connectivity, and state the Aanderaa–Karp–Rosenberg conjecture.

The adversary game

In the comparison model an algorithm learns about its input only by comparing two items, and its cost is the number of comparisons. Any such algorithm is a decision tree: each internal node compares two items, each branch is an outcome, each leaf gives an answer, and the worst-case cost is the tree's height.

An adversary argument proves a lower bound by playing against the algorithm. The adversary does not fix the input in advance. It answers each comparison as it likes, under one rule: its answers must stay consistent with some input. If it can keep two inputs with different correct outputs consistent through kk comparisons, every algorithm needs more than kk comparisons in the worst case.

Proof. Call an item a loser once it has lost a comparison. Suppose the algorithm stops while two items xx and yy have never lost, and answers xx. Raising yy above every other item is consistent with all the answers so far, since yy only ever won, and it makes yy the maximum: the answer was not certain. So when the algorithm stops, n−1n - 1 items have lost, and each comparison creates at most one new loser. Here no cunning adversary is even needed: the argument works whatever the answers.

Think first Counting leaves gives another bound: the tree must be able to output any of the nn items, so it has at least nn leaves and height at least ⌈log⁡2n⌉\lceil \log_2 n \rceil. Why is that so much weaker than n−1n - 1?

Counting outputs measures how much information the answer carries, log⁡2n\log_2 n bits. But the algorithm must also certify its answer: every other item must have lost a comparison, and certificates can be far longer than answers. The information bound is the right tool when certificates are short, as in searching a sorted array, and adversaries take over when they are not.

Maximum and minimum: ⌈3n/2⌉ − 2

Finding the maximum, then the minimum of the rest, costs (n−1)+(n−2)=2n−3(n - 1) + (n - 2) = 2n - 3 comparisons. Pairing does better: compare the items two by two, then race the winners for the maximum and the losers for the minimum.

python
def max_min(a):                     # a nonempty list; returns (max, min)
    n = len(a)
    if n % 2:                       # odd: the first item starts both races
        hi = lo = a[0]
        start = 1
    else:                           # even: one comparison seeds both races
        hi, lo = (a[0], a[1]) if a[0] > a[1] else (a[1], a[0])
        start = 2
    for i in range(start, n - 1, 2):
        big, small = (a[i], a[i + 1]) if a[i] > a[i + 1] else (a[i + 1], a[i])
        if big > hi:                # winners race for the maximum
            hi = big
        if small < lo:              # losers race for the minimum
            lo = small
    return hi, lo

Three comparisons per pair after the start: 1+3(n−2)/2=3n/2−21 + 3(n-2)/2 = 3n/2 - 2 for even nn and 3(n−1)/23(n-1)/2 for odd nn, which is ⌈3n/2⌉−2\lceil 3n/2 \rceil - 2 in both cases. For 100 items that is 148 comparisons instead of 197.

DerivationNo algorithm does better (Pohl, 1972)
  1. 2(n−2)+1+1=2n−2 units2(n - 2) + 1 + 1 = 2n - 2 \text{ units}

    Statuses and units. Give each item a status: N (never compared), W (has won, never lost), L (has lost, never won), or WL (both). At the end the maximum must be the only item that never lost and the minimum the only one that never won, so n−2n - 2 items are WL, one is W and one is L. Count one unit of information each time an item wins for the first time, and one each time it loses for the first time. The algorithm must collect

  2. The adversary's answers. N against N: either answer, 2 units. N against W or WL: the N item loses; N against L: the N item wins; either way 1 unit. W against W: one becomes WL, 1 unit; L against L likewise. W against L, W against WL, L against WL: the W item wins and the L item loses, which changes no status, 0 units. WL against WL: answer by the current values, 0 units.

  3. Consistency. The adversary keeps actual values and adjusts them as it goes: when a W item must win it is raised above everything, and when an L item must lose it is lowered below everything, while a fresh N item can be given any value. Raising an item that has never lost, or lowering one that has never won, contradicts no earlier answer.

  4. #comparisons  ≥  k+(2n−2−2k)  =  2n−2−k  ≥  2n−2−⌊n/2⌋  =  ⌈3n/2⌉−2\#\text{comparisons} \;\ge\; k + (2n - 2 - 2k) \;=\; 2n - 2 - k \;\ge\; 2n - 2 - \lfloor n/2 \rfloor \;=\; \lceil 3n/2 \rceil - 2

    Counting. Only N-against-N comparisons yield 2 units, and there are at most ⌊n/2⌋\lfloor n/2 \rfloor of them, since each uses up two untouched items. With kk of them, the other 2n−2−2k2n - 2 - 2k units need a comparison each:

Predict before you look

Exactly how many comparisons are necessary and sufficient, in the worst case, to find both the maximum and the minimum of 1,000 items?

Show the answer

1498

⌈3000/2⌉−2=1498\lceil 3000/2 \rceil - 2 = 1498: 500 comparisons within pairs, then 499 among the 500 winners and 499 among the 500 losers. The naive method uses 2⋅1000−3=19972 \cdot 1000 - 3 = 1997.

The second largest: a tournament

To find the second largest, run a knockout tournament. Its n−1n - 1 matches find the champion, and the runner-up must have lost to the champion directly: anything else lost to someone below the champion. So only the items the champion beat need a second look, and in a balanced bracket there are at most ⌈log⁡2n⌉\lceil \log_2 n \rceil of them.

python
def second_largest(a):              # len(a) >= 2, distinct values
    beaten = {i: [] for i in range(len(a))}    # whom each item has beaten
    players = list(range(len(a)))
    while len(players) > 1:         # knockout rounds; an odd one out gets a bye
        winners = []
        for i in range(0, len(players) - 1, 2):
            p, q = players[i], players[i + 1]
            w, l = (p, q) if a[p] > a[q] else (q, p)
            beaten[w].append(l)
            winners.append(w)
        if len(players) % 2:
            winners.append(players[-1])
        players = winners
    return max(a[j] for j in beaten[players[0]])   # the champion's victims

n−1n - 1 matches, then at most ⌈log⁡2n⌉−1\lceil \log_2 n \rceil - 1 comparisons among the champion's victims: n+⌈log⁡2n⌉−2n + \lceil \log_2 n \rceil - 2 in all, which is 18 for 16 items.

DerivationNo algorithm does better (Kislitsyn, 1964)
  1. #comparisons  =  #losses  ≥  (n−1)+(∣D∣−1)\#\text{comparisons} \;=\; \#\text{losses} \;\ge\; (n - 1) + (|D| - 1)

    Two kinds of losses. Every item except the maximum loses at least once. And every item that lost to the maximum, except the second largest, must also lose to some other item: if zz lost only to the maximum, raising zz to just below the maximum contradicts nothing and makes zz the second largest. Each comparison has exactly one loser, so with DD the set of items that lost to the maximum,

  2. w(winner)+w(loser)  ≤  2 w(winner)w(\text{winner}) + w(\text{loser}) \;\le\; 2\,w(\text{winner})

    An adversary that makes DD large. Every item starts with weight 1. When two items that have never lost meet, the heavier wins (ties either way) and absorbs the loser's weight; an item that has lost has weight 0 and loses to any item that has never lost; two items that have both lost are answered consistently with the past. Weights always sum to nn, and an item never known to be smaller than anything can be declared larger without contradiction. When both players had positive weight,

  3. ∣D∣≥⌈log⁡2n⌉⟹#comparisons  ≥  n+⌈log⁡2n⌉−2|D| \ge \lceil \log_2 n \rceil \quad\Longrightarrow\quad \#\text{comparisons} \;\ge\; n + \lceil \log_2 n \rceil - 2

    The champion's weight doubles at most once per victim. At the end the maximum is the only item that never lost, so it holds weight nn. Its weight grows only through wins over items of positive weight, each at most doubling it, so it beat at least ⌈log⁡2n⌉\lceil \log_2 n \rceil items directly:

nnmaximummaximum and minimumsecond largest
2111
3233
4344
5466
6577
The exact worst-case comparison counts for small nn, found by an exhaustive search over every comparison strategy against every consistent answer. Each column matches its formula: n−1n - 1, ⌈3n/2⌉−2\lceil 3n/2 \rceil - 2 and n+⌈log⁡2n⌉−2n + \lceil \log_2 n \rceil - 2. The last two columns first differ at n=7n = 7, with 9 and 8.

Searching, merging and evasive graphs

DerivationThree more adversaries
  1. k  ≥  ⌊log⁡2n⌋+1  =  ⌈log⁡2(n+1)⌉, which binary search achievesk \;\ge\; \lfloor \log_2 n \rfloor + 1 \;=\; \lceil \log_2(n + 1) \rceil, \text{ which binary search achieves}

    Searching for xx in a sorted array of nn items. The adversary never answers "equal", and after each comparison keeps the larger side as the positions where xx might be. From mm live positions at least ⌊m/2⌋\lfloor m/2 \rfloor survive, and the algorithm cannot stop while one survives, because xx could equal that item or be missing. So it needs ⌊n/2k⌋=0\lfloor n/2^k \rfloor = 0:

  2. (a1,b1), (b1,a2), (a2,b2), …, (an,bn)⟹2n−1 comparisons(a_1, b_1),\ (b_1, a_2),\ (a_2, b_2),\ \dots,\ (a_n, b_n) \quad\Longrightarrow\quad 2n - 1 \text{ comparisons}

    Merging a1<⋯<ana_1 < \dots < a_n with b1<⋯<bnb_1 < \dots < b_n. The adversary answers as if a1<b1<a2<b2<⋯<an<bna_1 < b_1 < a_2 < b_2 < \dots < a_n < b_n. Every pair that is adjacent in this order must be compared directly: if it never was, swapping the two values keeps both lists sorted and every other comparison's outcome unchanged, since no item lies between them, yet the merged order changes.

  3. a pair unasked  ⟹  yes-edges⏟disconnected and yes-edges+unasked pairs⏟connected are both consistent\text{a pair unasked} \;\Longrightarrow\; \underbrace{\text{yes-edges}}_{\text{disconnected}} \text{ and } \underbrace{\text{yes-edges} + \text{unasked pairs}}_{\text{connected}} \text{ are both consistent}

    Connectivity. An algorithm asks "is {u,v}\{u, v\} an edge?" about an unknown graph on nn vertices. The adversary answers "no" unless {u,v}\{u, v\} is the last unasked pair between the two current components of the yes-edges that contain uu and vv; then it answers "yes". Two facts hold throughout: every pair inside a component has been asked, since parts are joined only after all pairs between them are asked; and between any two components some pair is unasked, or the last one asked would have been answered "yes".

Check your understanding

Deciding whether nn numbers are all distinct needs Ω(nlog⁡n)\Omega(n\log n) steps in the algebraic decision-tree model (Ben-Or, 1983). A hash set decides it in O(n)O(n) expected time on a word RAM. Which explanation is right?

  1. The lower bound fails for large nn
  2. The lower bound counts only comparisons, and a hash set makes none
  3. The hash set's bound is amortized, while the lower bound is about the worst case
  4. Hashing computes memory addresses from the bits of the numbers, which no algebraic decision tree can do, so the bound does not apply
Show the answer

D. Hashing computes memory addresses from the bits of the numbers, which no algebraic decision tree can do, so the bound does not apply

A lower bound binds only the algorithms of its model. Algebraic decision trees branch on the signs of polynomials in the inputs; indexing memory by a computed hash value is outside the model. On the word RAM both deterministic O(nlog⁡n)O(n\log n), by sorting, and expected O(n)O(n), by hashing, are available.

Key takeaways

  • An adversary answers each comparison as it likes while staying consistent with some input; if two answers remain possible after kk comparisons, every algorithm needs more than kk.
  • The maximum needs exactly n−1n - 1 comparisons, the maximum and minimum ⌈3n/2⌉−2\lceil 3n/2 \rceil - 2 (pairing, against an adversary that gives at most one unit per comparison except between untouched items), and the second largest n+⌈log⁡2n⌉−2n + \lceil \log_2 n \rceil - 2 (a tournament, against a weight-doubling adversary).
  • Searching a sorted array needs ⌈log⁡2(n+1)⌉\lceil \log_2(n + 1) \rceil comparisons, merging two sorted lists of nn needs 2n−12n - 1, and graph connectivity needs all (n2)\binom{n}{2} edge questions.
  • A lower bound binds only its model: element distinctness needs Ω(nlog⁡n)\Omega(n\log n) steps for algebraic decision trees, yet hashing solves it in expected O(n)O(n) time on a word RAM.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

64 players compete, and each match has a winner and a loser. Whatever the format, at least how many matches are needed before the best player is known for sure?

  1. 6
  2. 32
  3. 63
  4. 64
Show the answer

C. 63

Every player except the champion must lose at least once, and each match has exactly one loser, so 63 matches are needed, and a knockout tournament uses exactly 63. Six is only the number of rounds of a balanced bracket.

Question 2

In the adversary proof of the ⌈3n/2⌉−2\lceil 3n/2 \rceil - 2 bound, which comparisons can give the algorithm 2 units of information?

  1. A comparison between two items that have both won before
  2. A comparison between two items that have never been compared
  3. A comparison between an item that has only won and one that has only lost
  4. Any comparison, if the algorithm chooses it well
Show the answer

B. A comparison between two items that have never been compared

Only an N-against-N comparison gives both items a new status. The adversary makes every other comparison worth at most one unit, and since each N-against-N comparison uses up two untouched items, there are at most ⌊n/2⌋\lfloor n/2 \rfloor of them.

Question 3

At least how many comparisons does finding the second largest of 16 items need in the worst case?

  1. 15
  2. 18
  3. 19
  4. 29
Show the answer

B. 18

n+⌈log⁡2n⌉−2=16+4−2=18n + \lceil \log_2 n \rceil - 2 = 16 + 4 - 2 = 18. A balanced tournament plays 15 matches; the champion beat 4 players directly, and 3 more comparisons pick the best of those 4. The weight adversary shows that no algorithm can always do better.

Question 4

When the adversary's order is a1<b1<a2<b2<⋯<an<bna_1 < b_1 < a_2 < b_2 < \dots < a_n < b_n, why must every merging algorithm compare bib_i with ai+1a_{i+1}?

  1. Because they come from different lists
  2. Because the standard merge happens to compare them
  3. Because merging must compare every pair of items from different lists
  4. Because no item lies between them: if they were never compared, swapping their values would change the merged order without changing any comparison's outcome
Show the answer

D. Because no item lies between them: if they were never compared, swapping their values would change the merged order without changing any comparison's outcome

The algorithm's knowledge is exactly the outcomes of its comparisons. Swapping two adjacent values leaves both lists sorted and every other outcome unchanged, so an algorithm that never compared them cannot tell the two inputs apart, yet their merged orders differ.

Further reading

  • D. E. Knuth, The Art of Computer Programming, Vol. 3: Sorting and Searching, 2nd ed. (Addison-Wesley, 1998), §5.3, "Optimum Sorting".
  • I. Pohl, "A sorting problem and its complexity," Communications of the ACM 15(6) (1972).
  • R. L. Rivest & J. Vuillemin, "On recognizing graph properties from adjacency matrices," Theoretical Computer Science 3(3) (1976).
  • J. Kahn, M. Saks & D. Sturtevant, "A topological approach to evasiveness," Combinatorica 4(4) (1984).
  • M. Ben-Or, "Lower bounds for algebraic computation trees," Proceedings of STOC (1983).