TExcelTAD
Home › Foundations of Algorithm Analysis › Indicator Random Variables

Indicator Random Variables

The previous lesson claimed that the expected number of hires is HnH_n 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 AA be an event. Its indicator is the random variable

I{A}={1if A occurs0otherwiseI\{A\} = \begin{cases} 1 & \text{if } A \text{ occurs} \\ 0 & \text{otherwise} \end{cases}

Lemma. E[I{A}]=Pr⁡[A]\mathbb{E}[I\{A\}] = \Pr[A].

The proof is one line: I{A}I\{A\} takes the value 1 with probability Pr⁡[A]\Pr[A] and 0 with probability 1−Pr⁡[A]1 - \Pr[A], so its expectation is 1⋅Pr⁡[A]+0⋅(1−Pr⁡[A])=Pr⁡[A]1 \cdot \Pr[A] + 0 \cdot (1 - \Pr[A]) = \Pr[A].

The other ingredient is linearity of expectation: for any random variables X1,…,XnX_1, \ldots, X_n on the same probability space,

E[∑i=1nXi]=∑i=1nE[Xi]\mathbb{E}\left[\sum_{i=1}^{n} X_i\right] = \sum_{i=1}^{n} \mathbb{E}[X_i]

It holds whether or not the XiX_i 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 XX be the number of hires and, for i=0,…,n−1i = 0, \ldots, n-1,

Xi=I{candidate i is hired},X=X0+X1+⋯+Xn−1X_i = I\{\text{candidate } i \text{ is hired}\}, \qquad X = X_0 + X_1 + \cdots + X_{n-1}

Candidate ii is hired exactly when it is the best among candidates 00 to ii. In a uniformly random order, those i+1i + 1 candidates are themselves in a uniformly random relative order, so each is equally likely to be the best of them: Pr⁡[Xi=1]=1i+1\Pr[X_i = 1] = \frac{1}{i+1}. Then

E[X]=∑i=0n−1E[Xi]=∑i=0n−11i+1=Hn\mathbb{E}[X] = \sum_{i=0}^{n-1} \mathbb{E}[X_i] = \sum_{i=0}^{n-1} \frac{1}{i+1} = H_n

The program below checks each indicator separately for n=5n = 5: it walks through all 5!=1205! = 120 orders and counts, for each position, the orders that hire there.

python · try it yourself
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

13760=H5\frac{137}{60} = H_5. Notice what the proof did not need: the distribution of XX (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 aa is a pair of positions i<ji < j with a[i]>a[j]a[i] > a[j]. 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 nn distinct values have?

Define one indicator per pair: Yij=I{a[i]>a[j]}Y_{ij} = I\{a[i] > a[j]\} for 0≤i<j≤n−10 \le i < j \le n - 1. For a uniformly random permutation the two values at positions ii and jj are equally likely to be in either order, so Pr⁡[Yij=1]=12\Pr[Y_{ij} = 1] = \frac{1}{2}. There are (n2)\binom{n}{2} pairs, hence

E[inversions]=∑i<jE[Yij]=(n2)⋅12=n(n−1)4\mathbb{E}[\text{inversions}] = \sum_{i<j} \mathbb{E}[Y_{ij}] = \binom{n}{2} \cdot \frac{1}{2} = \frac{n(n-1)}{4}

So on a random input insertion sort does about n2/4n^2/4 shifts: half of the worst case n(n−1)/2n(n-1)/2, still Θ(n2)\Theta(n^2). The average case of insertion sort is no better in order of growth than its worst case.

python · try it yourself
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 nn, simulation only supports it.

Fixed points: dependent indicators, same easy answer

A fixed point of a permutation pp of 0,…,n−10, \ldots, n-1 is a position ii with p[i]=ip[i] = i. Think of nn people taking back nn coats at random: a fixed point is someone who gets their own coat. With Zi=I{p[i]=i}Z_i = I\{p[i] = i\} and Pr⁡[Zi=1]=1n\Pr[Z_i = 1] = \frac{1}{n} (position ii is equally likely to receive any of the nn values),

E[fixed points]=∑i=0n−11n=1\mathbb{E}[\text{fixed points}] = \sum_{i=0}^{n-1} \frac{1}{n} = 1

for every nn. These indicators are clearly dependent. If the first n−1n - 1 people all have their own coats, the last one must too. Even for two positions, Pr⁡[Z0=1 and Z1=1]=1n(n−1)\Pr[Z_0 = 1 \text{ and } Z_1 = 1] = \frac{1}{n(n-1)}, which is not 1n⋅1n\frac{1}{n} \cdot \frac{1}{n}. Linearity does not care.

python · try it yourself
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 38\frac{3}{8} for n=4n = 4 and tends to 1e\frac{1}{e}; that needs inclusion-exclusion, not linearity. Linearity gives expectations, and only expectations.

Overlapping patterns in coin flips

Flip a fair coin nn times and count the positions ii (0≤i≤n−20 \le i \le n - 2) where flips ii and i+1i + 1 are both heads; in HHH there are two such positions. Each indicator Wi=I{flips i,i+1 are heads}W_i = I\{\text{flips } i, i+1 \text{ are heads}\} has probability 14\frac{1}{4}, so the expected count is n−14\frac{n-1}{4}. Neighbouring indicators share a flip and are dependent (W0=1W_0 = 1 makes W1=1W_1 = 1 twice as likely), and the answer is still just the sum.

python · try it yourself
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

  1. Name the random quantity XX you want the expectation of.
  2. Write X=∑iXiX = \sum_i X_i with each XiX_i the indicator of a simple event.
  3. Find Pr⁡[Xi=1]\Pr[X_i = 1], usually by a symmetry argument ("each of the kk candidates is equally likely to be the best").
  4. Add the probabilities.

The method gives the mean only. It says nothing about how likely XX is to be far from its mean; for that you need variances or tail bounds, which the Randomized Algorithms course develops. And E[XY]=E[X] E[Y]\mathbb{E}[XY] = \mathbb{E}[X]\,\mathbb{E}[Y] does need independence: linearity is about sums, not products.

Test yourself

Why is E[I{A}]=Pr⁡[A]\mathbb{E}[I\{A\}] = \Pr[A]?

  1. Because indicators are always independent
  2. Because I{A}I\{A\} is 1 with probability Pr⁡[A]\Pr[A] and 0 otherwise, so its mean is 1⋅Pr⁡[A]+01 \cdot \Pr[A] + 0
  3. Because of the law of large numbers
  4. It only holds when Pr⁡[A]=12\Pr[A] = \frac{1}{2}

What is the expected number of inversions in a uniformly random permutation of nn distinct values?

  1. n/2n/2
  2. n(n−1)/4n(n-1)/4
  3. n(n−1)/2n(n-1)/2
  4. nln⁡nn \ln n

The indicators Zi=I{p[i]=i}Z_i = I\{p[i] = i\} for fixed points of a random permutation are dependent. What does that change about E[∑iZi]\mathbb{E}[\sum_i Z_i]?

  1. Nothing: linearity of expectation holds without independence, so the answer is 1
  2. The expectation becomes 1n\frac{1}{n}
  3. The expectation cannot be computed
  4. The expectation becomes 1/e1/e

In the hiring problem, why is Pr⁡[candidate i is hired]=1i+1\Pr[\text{candidate } i \text{ is hired}] = \frac{1}{i+1} (0-based ii)?

  1. Because candidate ii is hired exactly when it is the best of the first i+1i + 1 candidates, and in a random order each of them is equally likely to be that best
  2. Because each candidate is hired independently with that probability by design
  3. Because there are i+1i + 1 hires before it
  4. Because of the birthday paradox