Technique · Interview · hard
Probability & Expected-Value DP (linearity of expectation)
Compute probabilities or expectations by DP over states. Use linearity of expectation to split a hard expectation into a sum of easy per-element or per-pair indicator probabilities.
0/12 solved
Recognise it
The signal
'return the probability that ...'
1Brute force
Enumerate all outcomes: exponential.
2The observation
The number of outcomes, plus dependencies between events.
3Why it works
E[X + Y] = E[X] + E[Y] even when X and Y are dependent; dp[state] = sum over transitions of p * dp[next].
Reach for it when
- +'expected number of ...'
- +answer within 1e-5, or modulo p as P*Q-1
- +random walks / random draws
Not when
- ×the state graph has cycles (needs gaussian-elimination or a closed form)
- ×a huge threshold where the answer converges (soup-servings returns 1 for large n)
Practice
- New 21 GameMedium
- Soup ServingsMedium
- Knight Probability in ChessboardMedium
- Airplane Seat Assignment ProbabilityMedium
- Dice ProbabilityCSESMedium
- Frog Position After T SecondsHard
- Moving RobotsCSESHard
- Candy LotteryCSESHard
- Inversion ProbabilityCSESHard
- Broken robotCodeforces2400
- Beautiful MirrorsCodeforces2100
- Steps to OneCodeforces2300
Pitfalls
Misconceptions
- !E[max] is not the max of the expectations; compute P(max <= k) and take differences
- !probabilities mod p need modular inverses
Go deeper4 combinations · resources
Combinations
Probability & Expected-Value DP (linearity of expectation)+1D / Fibonacci-style+Sliding Window
probability over a running total with uniform draws and a stopping threshold
- Probability & Expected-Value DP (linearity of expectation):
- P(i) = (1/W) * sum of P(i - k) over k = 1..W
- 1D / Fibonacci-style:
- the probability DP over points
- Sliding Window:
- keep that sum in O(1) per step
Probability & Expected-Value DP (linearity of expectation)+Contribution Technique (sum over all subarrays/pairs)
expected number of inversions / empty squares / matches
- Probability & Expected-Value DP (linearity of expectation):
- linearity: sum the indicator probabilities
- Contribution Technique (sum over all subarrays/pairs):
- split the total into per-pair or per-square indicators
Probability & Expected-Value DP (linearity of expectation)+Gaussian Elimination (mod p / reals) & Matrix-Tree Theorem
expected steps of a random walk with self-loops or sideways moves
- Probability & Expected-Value DP (linearity of expectation):
- E[state] = 1 + sum of p * E[next]
- Gaussian Elimination (mod p / reals) & Matrix-Tree Theorem:
- solve the system when states reference each other
Probability & Expected-Value DP (linearity of expectation)+Tree DFS (Paths & Recursion)
probability that a random walk on a tree is at vertex v at time t
- Probability & Expected-Value DP (linearity of expectation):
- the probability multiplies by 1/(#unvisited children) at each step
- Tree DFS (Paths & Recursion):
- walk from the root with depth/time