Expected cost of randomised algorithms
About this lesson
Some algorithms flip coins on purpose, so the same input can cost a different amount each run. Here you shuffle a list of 4 numbers, count how often the best-so-far changes, and find the expected cost two ways: by averaging all 24 equally likely shuffles, and by adding one small indicator variable per position (linearity of expectation). The Software lesson "How fast is fast? Big O" introduces counting steps, and the Maths lessons "Logarithms and exponents" and "Recurrences: describing a value by smaller cases" cover the ln n that appears at the end.
Random choices, random cost
A randomised algorithm makes random choices as it runs. This one shuffles the list, then scans it and counts how often best changes. That count is our cost. Same input, different shuffles, different costs.
cost model: one unit each time best is set 1 import random 2 def count_updates(a): 3 random.shuffle(a) 4 best, count = a[0], 1 5 for x in a[1:]: 6 if x > best: 7 best = x 8 count += 1 9 return count input a = [3, 1, 4, 2], n = 4 random.shuffle(a) reorders a in place
Read the lesson step by step
Random choices, random cost
A randomised algorithm makes random choices as it runs. This one shuffles the list, then scans it and counts how often best changes. That count is our cost. Same input, different shuffles, different costs.
cost model: one unit each time best is set 1 import random 2 def count_updates(a): 3 random.shuffle(a) 4 best, count = a[0], 1 5 for x in a[1:]: 6 if x > best: 7 best = x 8 count += 1 9 return count input a = [3, 1, 4, 2], n = 4 random.shuffle(a) reorders a in placeOne run: 2 updates
The shuffle gives [2, 4, 1, 3]. best starts at 2, count 1. Then 4 beats 2: an update. 1 and 3 do not beat 4. This run costs 2 updates.
order [2, 4, 1, 3] i=1 x=2 first: best = 2, count = 1 i=2 x=4 4 > 2: best = 4, count = 2 i=3 x=1 1 < 4: skip i=4 x=3 3 < 4: skip return 2Unlucky: 4 updates
Run it again on the same input. This time the shuffle lands sorted: [1, 2, 3, 4]. Every number beats the one before, so best changes at every position: 4 updates, the most possible.
order [1, 2, 3, 4] i=1 x=1 first: best = 1, count = 1 i=2 x=2 2 > 1: best = 2, count = 2 i=3 x=3 3 > 2: best = 3, count = 3 i=4 x=4 4 > 3: best = 4, count = 4 return 4Lucky: 1 update
Once more: [4, 1, 3, 2]. The largest number comes first, nothing beats it, and the cost is 1. So the cost is a random variable: a number that depends on chance.
order [4, 1, 3, 2] i=1 x=4 first: best = 4, count = 1 i=2 x=1 1 < 4: skip i=3 x=3 3 < 4: skip i=4 x=2 2 < 4: skip return 1Try every shuffle
A fair shuffle makes all 24 orders of 4 numbers equally likely. Run each once and drop a cube on the bar for its cost: 6, 11, 6, 1 runs cost 1, 2, 3 and 4 updates.
4! = 24 orders, each with chance 1/24 updates runs 1 6 2 11 3 6 4 1 total 24 runsExpected cost: the average
Expected cost is the average over all equally likely choices. The 24 runs make 50 updates in total, so E[cost] = 50/24 = 25/12 ≈ 2.08. The marker sits where the bars would balance.
E[X] = sum of (cost × chance) = 1·6/24 + 2·11/24 + 3·6/24 + 4·1/24 = (6 + 22 + 18 + 4)/24 = 50/24 = 25/12 ≈ 2.08 updates worst case 4, best case 1One lamp per position
Listing orders gets slow. Instead give position i a lamp X_i that shows 1 if best changes there. Run [1, 3, 2, 4]: lamps 1, 2 and 4 light, and the cost is their sum, 1 + 1 + 0 + 1 = 3.
indicator variable: X_i = 1 if position i updates best, else 0 cost X = X_1 + X_2 + X_3 + X_4 order [1, 3, 2, 4] i=1 x=1 first: best = 1, count = 1 i=2 x=3 3 > 1: best = 3, count = 2 i=3 x=2 2 < 3: skip i=4 x=4 4 > 3: best = 4, count = 3 return 3Each lamp: chance 1/i
Position i updates only if it holds the largest of the first i numbers. In a fair shuffle that largest one is equally likely to be in any of those i places, so Pr[X_i = 1] = 1/i: lamps glow 1, ½, ⅓ and ¼.
Pr[X_i = 1] = 1/i, and E[X_i] = 1·Pr[X_i = 1] + 0 = 1/i check against the 24 orders: X_1 is on in 24 of 24 = 1/1 X_2 is on in 12 of 24 = 1/2 X_3 is on in 8 of 24 = 1/3 X_4 is on in 6 of 24 = 1/4Add the lamps
Linearity of expectation: the average of a sum is the sum of the averages. So E[cost] = 1 + ½ + ⅓ + ¼ = 25/12, the same balance point as the 24 runs, with no list at all.
E[X_1 + X_2 + X_3 + X_4] = E[X_1] + E[X_2] + E[X_3] + E[X_4] = 1 + 1/2 + 1/3 + 1/4 = (12 + 6 + 4 + 3)/12 = 25/12 = (24 + 12 + 8 + 6)/24, the 24-run total 50 linearity holds even when the X_i depend on each otherAny n: about ln n
The same sum works for any list size n: E[cost] = 1 + ½ + ... + 1/n, which grows like ln n. For n = 1000 that is about 7.49 updates, while the unlucky worst case is 1000. Expected O(log n).
E[cost] = H_n = 1 + 1/2 + 1/3 + ... + 1/n ln(n + 1) < H_n ≤ ln n + 1, so H_n ~ ln n n = 4 H_4 = 2.08 n = 100 H_100 ≈ 5.19 n = 1000 H_1000 ≈ 7.49 (worst case 1000)No input is unlucky
The luck is in the shuffle, not the data. Even a sorted list, the worst input for a plain scan, gets shuffled first, so every input has the same expected cost, 25/12. Expected cost averages over the coin flips only.
input [1, 2, 3, 4]: without the shuffle, 4 updates every time with the shuffle: any of the 24 orders, e.g. [4, 2, 3, 1] expected cost for EVERY input: 25/12 ≈ 2.08 average case (random inputs) ≠ expected cost (random choices)
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01count_updates shuffles [3, 1, 4, 2] and the shuffle gives [2, 3, 1, 4]. How many updates does this run cost?
best is set to 2 (count 1), then 3 beats 2 (count 2), 1 does not beat 3, and 4 beats 3 (count 3). The run costs 3 updates.
02Over all 24 orders of 4 different numbers, the costs 1, 2, 3 and 4 happen 6, 11, 6 and 1 times. What is the expected cost?
Add up every run's cost and divide by the number of equally likely runs: (1·6 + 2·11 + 3·6 + 4·1)/24 = 50/24 = 25/12.
03Why is the chance that position 3 updates best exactly 1/3 in a fair shuffle?
In a fair shuffle every arrangement of the first 3 numbers is equally likely, so the largest of them sits in place 3 one time in 3. That is 8 of the 24 orders.
04Linearity of expectation says E[X₁ + X₂ + X₃ + X₄] = E[X₁] + E[X₂] + E[X₃] + E[X₄]. When does it hold?
Linearity of expectation needs no independence and no special values. That is what makes indicator variables so useful: split a cost into simple pieces, find each piece's average, add.
05A plain scan of a sorted list always costs n updates. With the shuffle first, what is the expected cost on that same sorted list?
The shuffle throws away the input order, so every input, sorted or not, has the same expected cost H_n = 1 + 1/2 + ... + 1/n, which grows like ln n (about 7.49 for n = 1000).
Glossary
- Randomised algorithm
- An algorithm that makes random choices as it runs, such as shuffling its input or picking a random pivot.
- Random variable
- A number whose value depends on chance, like the cost of one run of a randomised algorithm.
- Expected value, E[X]
- The average of a random variable: each possible value times its chance, added up.
- Expected cost
- The expected value of an algorithm's cost on one input, averaged over its own random choices.
- Indicator variable
- A random variable that is 1 when an event happens and 0 when it does not. Its expected value is the event's chance.
- Linearity of expectation
- E[X + Y] = E[X] + E[Y] for any random variables, even ones that depend on each other.
- Harmonic number, Hₙ
- 1 + 1/2 + 1/3 + ... + 1/n. It grows like ln n.
- Average case
- Cost averaged over random inputs. Different from expected cost, which averages over the algorithm's own coin flips for a fixed input.
Notes and sources
- Cost here counts the times best is set (line 4 once, then line 7 on each update). Comparisons are always n - 1 = 3, whatever the order, so they are not the interesting part. CLRS calls this the hiring problem: each update is a hire.
- Expected value E[X] = sum of each value times its chance. A fair shuffle gives every order of the list the same chance, so here the expectation is a plain average over the 24 orders.
- Linearity of expectation, E[X + Y] = E[X] + E[Y], holds for any random variables, even dependent ones. MIT 6.006 uses the same indicator trick to show hash table chains have O(1) expected length.
- H_n = 1 + 1/2 + ... + 1/n satisfies ln(n + 1) < H_n ≤ ln n + 1, so H_n ~ ln n (Sedgewick and Wayne; CLRS appendix A). For n = 1000, H_n ≈ 7.49.
- The same idea gives randomised quicksort its guarantee: it shuffles first, so every input takes about 2n ln n compares on average, though one unlucky run can still take about n²/2.
- The code is real Python 3. random.shuffle works in place, so it changes the caller's list; pass a copy, count_updates(a[:]), to keep the original order.
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 5: Probabilistic Analysis and Randomized Algorithms
- MIT 6.006 Introduction to Algorithms (Spring 2020), Lecture 4: Hashing (indicator random variables, expected chain length)
- Sedgewick and Wayne, Algorithms 4th ed., §2.3 Quicksort (random shuffle, ~2N ln N compares on average)
- Sedgewick and Wayne, Algorithms 4th ed., Algorithms and data structures cheatsheet (harmonic sum ~ ln n)
- Python Standard Library: random, random.shuffle
Quiz Unlocks after the last step.