Indicator Random Variables
The previous lesson claimed that the expected number of hires is and waved at "linearity". This lesson makes that step precise with the single most useful trick in probabilistic analysis: the indicator random variable. The recipe is always the same. Write the quantity you care about as a sum of 0/1 variables, find the probability of each one, and add. You never need the distribution of the total, and you never need the pieces to be independent.
Linearity and Indicator Variables introduces the tool from the probability side; here it is used to analyse algorithms, with every result checked exactly by enumerating all inputs.
Definition
Let be an event. Its indicator is the random variable
Lemma. .
The proof is one line: takes the value 1 with probability and 0 with probability , so its expectation is .
The other ingredient is linearity of expectation: for any random variables on the same probability space,
It holds whether or not the are independent. That is what makes the method so strong: the events in algorithm analysis are almost never independent.
The hiring problem, done properly
Candidates arrive in a uniformly random order and the procedure hires whenever a candidate beats everyone seen so far (The Hiring Problem). Let be the number of hires and, for ,
Candidate is hired exactly when it is the best among candidates to . In a uniformly random order, those candidates are themselves in a uniformly random relative order, so each is equally likely to be the best of them: . Then
The program below checks each indicator separately for : it walks through all orders and counts, for each position, the orders that hire there.
from fractions import Fraction
from itertools import permutations
from math import factorial
n = 5
hired_count = [0] * n # how many orders hire candidate i
for order in permutations(range(n)):
best = -1
for i, s in enumerate(order):
if s > best:
best = s
hired_count[i] += 1 # indicator X_i = 1 for this order
total = factorial(n)
for i in range(n):
print(f"Pr[candidate {i} hired] = E[X_{i}] = {Fraction(hired_count[i], total)}")
print("sum =", sum(Fraction(c, total) for c in hired_count))Pr[candidate 0 hired] = E[X_0] = 1
Pr[candidate 1 hired] = E[X_1] = 1/2
Pr[candidate 2 hired] = E[X_2] = 1/3
Pr[candidate 3 hired] = E[X_3] = 1/4
Pr[candidate 4 hired] = E[X_4] = 1/5
sum = 137/60
. Notice what the proof did not need: the distribution of (how likely exactly 3 hires is), which is messy. The indicators are not independent either: if candidate 4 is hired, candidate 4 is the maximum, which changes the odds for the others. None of that matters for the expectation.
Expected inversions
An inversion of an array is a pair of positions with . Inversions measure how unsorted an array is, and they are exactly the number of shifts insertion sort performs (see Counting Steps Exactly). How many does a random permutation of distinct values have?
Define one indicator per pair: for . For a uniformly random permutation the two values at positions and are equally likely to be in either order, so . There are pairs, hence
So on a random input insertion sort does about shifts: half of the worst case , still . The average case of insertion sort is no better in order of growth than its worst case.
from fractions import Fraction
from itertools import permutations
from math import factorial
import random
def inversions(a):
return sum(1 for i in range(len(a)) for j in range(i + 1, len(a)) if a[i] > a[j])
for n in range(1, 7):
avg = Fraction(sum(inversions(p) for p in permutations(range(n))), factorial(n))
print(f"n = {n}: average inversions {str(avg):4} n(n-1)/4 = {Fraction(n * (n - 1), 4)}")
rng = random.Random(7)
n, trials = 50, 1000
total = 0
for _ in range(trials):
a = list(range(n))
rng.shuffle(a)
total += inversions(a)
print(f"n = {n}: simulated average {total / trials:.1f}, formula {n * (n - 1) / 4}")n = 1: average inversions 0 n(n-1)/4 = 0
n = 2: average inversions 1/2 n(n-1)/4 = 1/2
n = 3: average inversions 3/2 n(n-1)/4 = 3/2
n = 4: average inversions 3 n(n-1)/4 = 3
n = 5: average inversions 5 n(n-1)/4 = 5
n = 6: average inversions 15/2 n(n-1)/4 = 15/2
n = 50: simulated average 610.5, formula 612.5
The exact rows match the formula; the simulated row is close, as a sample average should be. Exact enumeration proves the formula for small , simulation only supports it.
Fixed points: dependent indicators, same easy answer
A fixed point of a permutation of is a position with . Think of people taking back coats at random: a fixed point is someone who gets their own coat. With and (position is equally likely to receive any of the values),
for every . These indicators are clearly dependent. If the first people all have their own coats, the last one must too. Even for two positions, , which is not . Linearity does not care.
from fractions import Fraction
from itertools import permutations
from math import factorial
n = 4
perms = list(permutations(range(n)))
N = factorial(n)
def fixed(p, i):
return 1 if p[i] == i else 0
p0 = Fraction(sum(fixed(p, 0) for p in perms), N)
p01 = Fraction(sum(fixed(p, 0) * fixed(p, 1) for p in perms), N)
print(f"Pr[Z_0 = 1] = {p0}")
print(f"Pr[Z_0 = 1 and Z_1 = 1] = {p01}, but Pr[Z_0 = 1] * Pr[Z_1 = 1] = {p0 * p0}")
none = Fraction(sum(1 for p in perms if all(p[i] != i for i in range(n))), N)
print(f"Pr[no fixed point] = {none}")
for n in range(1, 8):
perms = permutations(range(n))
avg = Fraction(sum(sum(1 for i in range(n) if p[i] == i) for p in perms), factorial(n))
print(f"n = {n}: expected fixed points = {avg}")Pr[Z_0 = 1] = 1/4
Pr[Z_0 = 1 and Z_1 = 1] = 1/12, but Pr[Z_0 = 1] * Pr[Z_1 = 1] = 1/16
Pr[no fixed point] = 3/8
n = 1: expected fixed points = 1
n = 2: expected fixed points = 1
n = 3: expected fixed points = 1
n = 4: expected fixed points = 1
n = 5: expected fixed points = 1
n = 6: expected fixed points = 1
n = 7: expected fixed points = 1
The probability of no fixed point (a derangement) is for and tends to ; that needs inclusion-exclusion, not linearity. Linearity gives expectations, and only expectations.
Overlapping patterns in coin flips
Flip a fair coin times and count the positions () where flips and are both heads; in HHH there are two such positions. Each indicator has probability , so the expected count is . Neighbouring indicators share a flip and are dependent ( makes twice as likely), and the answer is still just the sum.
import random
def count_hh(flips):
# number of positions i with heads at i and at i + 1 (overlapping pairs count)
return sum(1 for i in range(len(flips) - 1) if flips[i] == flips[i + 1] == "H")
rng = random.Random(7)
n, trials = 40, 20000
total = 0
for _ in range(trials):
flips = [rng.choice("HT") for _ in range(n)]
total += count_hh(flips)
print(f"average HH pairs in {n} flips: {total / trials:.3f}")
print(f"(n - 1) / 4 = {(n - 1) / 4}")average HH pairs in 40 flips: 9.787
(n - 1) / 4 = 9.75
The recipe, and where it stops
- Name the random quantity you want the expectation of.
- Write with each the indicator of a simple event.
- Find , usually by a symmetry argument ("each of the candidates is equally likely to be the best").
- Add the probabilities.
The method gives the mean only. It says nothing about how likely is to be far from its mean; for that you need variances or tail bounds, which the Randomized Algorithms course develops. And does need independence: linearity is about sums, not products.
Test yourself
Why is ?
- Because indicators are always independent
- Because is 1 with probability and 0 otherwise, so its mean is
- Because of the law of large numbers
- It only holds when
What is the expected number of inversions in a uniformly random permutation of distinct values?
The indicators for fixed points of a random permutation are dependent. What does that change about ?
- Nothing: linearity of expectation holds without independence, so the answer is 1
- The expectation becomes
- The expectation cannot be computed
- The expectation becomes
In the hiring problem, why is (0-based )?
- Because candidate is hired exactly when it is the best of the first candidates, and in a random order each of them is equally likely to be that best
- Because each candidate is hired independently with that probability by design
- Because there are hires before it
- Because of the birthday paradox