Counting, Probability & Games
Dynamic programs that count, average, and decide who wins.
How many ways are there to tile a board with dominoes? About , far too many to list, yet a five-line dynamic program counts them exactly. Replace the minimum in a DP by a sum and it counts; replace it by an average and it computes expectations; replace it by "is there a move to a losing position?" and it decides who wins a game.
What you’ll learn
- Count objects with a DP whose cases are disjoint and exhaustive, and prove it exact by unique decomposition.
- Count combinations rather than orderings by building each object in one canonical order, and keep counts modulo a prime safely.
- Compute probabilities and expected values by first-step analysis, including states with self-loops.
- Classify game positions as winning or losing over the game DAG, and value zero-sum games with minimax over positions.
- Recognize "how many ways", "expected number" and "who wins" problems, and the look-alikes where these DPs fail.
Counting: the same table, with a sum
In an optimization DP each state keeps the best of its choices. In a counting DP it keeps the number of ways, and the transition adds the counts of the choices instead of taking their minimum:
The states, the fill order and the running time stay the same; only the operator changes.
Take tilings of a board by dominoes, and look at the leftmost column. Either one vertical domino covers it, leaving a board, or two horizontal dominoes cover the first two columns, leaving a board. No tiling does both, and every tiling does one of them.
The same pattern counts lattice paths. A robot walks from the top-left cell of a grid to the bottom-right cell, moving right or down and avoiding blocked cells. Classify each path by its last step, which arrives from above or from the left:
MOD = 10**9 + 7
def count_paths(grid): # '.' free, '#' blocked; moves: right or down
R, C = len(grid), len(grid[0])
ways = [[0] * C for _ in range(R)]
for r in range(R):
for c in range(C):
if grid[r][c] == '#':
continue # no path ends on a blocked cell
if r == 0 and c == 0:
ways[r][c] = 1 # the path that has not moved yet
continue
up = ways[r - 1][c] if r > 0 else 0
left = ways[r][c - 1] if c > 0 else 0
ways[r][c] = (up + left) % MOD # last step from above or from the left
return ways[R - 1][C - 1]time for rows and columns. On a grid with no blocked cell it returns . The count is reported modulo the prime because counts grow exponentially; the next step gives the rules.
Think first Count the binary strings of length with no two adjacent 1s. Which classification gives a recurrence, and what is it?
Classify by the last character. A valid string ending in 0 is any valid string of length followed by 0. One ending in 1 must have a 0 before it, so it is any valid string of length followed by 01. The two classes are disjoint and exhaustive, so with and , which gives : Fibonacci once more.
Count each object once
How many ways are there to pay 6 with coins of value 1, 3 and 4? If and are the same payment, there are 4 ways; if order matters, there are 9. Both counts come from the same one-dimensional array of coin change, with the two loops nested in opposite orders:
def combinations(coins, amount):
ways = [1] + [0] * amount # ways[0] = 1: the empty payment
for c in coins: # coins outside: one order per multiset
for a in range(c, amount + 1):
ways[a] = (ways[a] + ways[a - c]) % MOD
return ways[amount]
def sequences(coins, amount):
ways = [1] + [0] * amount
for a in range(1, amount + 1): # amounts outside: classify by the last coin
for c in coins:
if c <= a:
ways[a] = (ways[a] + ways[a - c]) % MOD
return ways[amount]With the coins outside, the array after coin counts payments that use only the coins processed so far, so each multiset is built in exactly one order: all the 1s, then all the 3s, then all the 4s. With the amounts outside, classifies payments by their last coin, so and are different. Both take time for coins and amount .
With coins of value 1 and 2, in how many ways can you pay 10 if the order of the coins does not matter?
Show the answer
6 ways
A multiset of 1s and 2s summing to 10 is fixed by its number of 2s, which can be : 6 ways. Counting orders instead gives 89, the stairs count : the same coins, about fifteen times as many sequences.
Expected values: first-step analysis
Randomness turns counting into averaging. Suppose a process moves from state to state with probability , each step costing 1. Conditioning on the first step (the law of total expectation) gives
with at the states where the process stops. When every step leads to a "later" state, this is a DP filled backward from the stopping states.
def expected_rolls(n): # fair die; stop once the total is n or more
E = [0.0] * (n + 6) # E[s] = 0 for s >= n: nothing left to do
for s in range(n - 1, -1, -1): # s depends on s+1 .. s+6, so fill backward
E[s] = 1 + sum(E[s + d] for d in range(1, 7)) / 6
return E[0]Roll a fair die and add the results: is the expected number of further rolls, from total , until the total reaches . time with six terms per state. For it returns about , a little more than , since each roll adds 3.5 on average and the last one overshoots.
Self-loops. Now roll a die until every face has appeared. The state is , the number of distinct faces seen so far. A roll that repeats an old face, with probability , leaves the state unchanged, so appears on both sides of its own equation. Guess first:
On average, how many rolls of a fair die does it take to see all six faces at least once?
Show the answer
14.7 rolls
, as the derivation below shows. The last new face alone takes 6 rolls on average.
From state , a roll shows an old face with probability (stay) or a new one with probability (move to ):
Move the self-loop term to the left and divide by :
Unroll from :
With faces the same steps give , where is the -th harmonic number: about 519 draws to collect 100 coupons.
Who wins? DP over game positions
Two players alternate moves. There is no chance, no hidden information and no draw, and a player who cannot move loses (normal play). Then every position is a win or a loss for the player about to move, and a DP over the positions decides which:
- a position is losing if every move leads to a winning position (in particular, if there is no move at all);
- a position is winning if some move leads to a losing position.
A subtraction game. A pile holds stones; a move removes 1, 3 or 4 of them; whoever takes the last stone wins. Position 0 is losing (no move), 1 is winning (take 1), 2 is losing (its only move leads to 1), and so on:
def winning(n, moves=(1, 3, 4)):
win = [False] * (n + 1) # win[0] = False: no move, so the player to move loses
for k in range(1, n + 1):
win[k] = any(m <= k and not win[k - m] for m in moves)
return wintime for the move set . The losing positions are : exactly the with . Periodicity is no accident: the Optimal lesson on games proves that every finite subtraction game becomes periodic.
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | |
|---|---|---|---|---|---|---|---|---|---|---|
| outcome | L | W | L | W | W | W | W | L | W | L |
| a winning move | none | take 1 | none | take 1 | take 4 | take 3 | take 4 | none | take 1 | none |
With the moves , it is your turn and the pile holds 10 stones. Which moves guarantee you a win?
- Taking 1 or taking 3
- Only taking 4
- Only taking 1
- None: 10 is a losing position
Show the answer
A. Taking 1 or taking 3
and are both losing positions ( and ), so either move hands your opponent a loss. Taking 4 leaves 6, a winning position for them.
Scored games: minimax over positions. In coins in a line, coins lie in a row and the players alternately take a coin from either end, each trying to maximize their own total. Let be the largest margin (own total minus the opponent's) that the player to move can guarantee on the coins , inclusive. Taking the left coin gains and hands the opponent , so
an interval DP with states and time.
The tree has leaves, but it repeats positions: taking the left coin and then the right one leaves the same coins as the other order. Evaluating each position once is memoization, and for 40 coins it means 820 intervals instead of leaves. Games that are sums of independent games, such as several piles played side by side, need one more idea, Grundy numbers, in the Optimal lesson on games.
Recognizing it
Signals in a problem statement:
- "how many ways", "the number of distinct …", "count … modulo ": a counting DP, or a formula when the structure is simple enough;
- "the probability that", "the expected number of steps", "on average": first-step analysis over the states of the process;
- "both players play optimally", "who wins", "the largest score the first player can guarantee": win/lose or minimax DP over positions;
- a small state space: states times work per state must fit the time limit (rule of thumb: about simple operations per second in a compiled language).
| Problem (in brief) | State and transition | Key idea | Cost |
|---|---|---|---|
| Tilings of a board, or ways to climb stairs by 1 or 2, modulo a prime | classify by the first piece | ; by matrix powers | |
| Ways to pay an amount, order irrelevant | , coins outside | build each multiset in coin order | |
| Lattice paths avoiding blocked cells | up left | classify by the last step | |
| Expected rolls to reach a total, or to see every face | , backward | first-step analysis; solve the self-loops | |
| Who wins a subtraction game, or coins in a line | W/L over ; over intervals | winning iff some move reaches a losing position | ; |
Key takeaways
- A counting DP is an optimization DP with the minimum replaced by a sum. It is exact when the cases at every state are disjoint and exhaustive, and the base case counts the empty object once.
- To count unordered objects, build each in one canonical order: with the coins outside the amounts, coin change counts combinations; with the amounts outside, ordered sequences.
- Expectations follow first-step analysis, , filled backward; a self-loop is removed by solving for , and general cycles need a linear system.
- A game position is losing iff every move leads to a winning position; scored games use minimax over positions, which costs the number of positions rather than the size of the game tree.
- Reduce modulo the prime after every operation, and never divide or compare reduced counts.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
This code counts payments: for a in 1..amount: for c in coins: if c <= a: ways[a] += ways[a - c], with ways[0] = 1. What does it return for coins and amount 3?
- 2
- 3
- 4
- 1
Show the answer
B. 3
With the amounts outside, the code classifies payments by their last coin, so it counts ordered sequences: , and . Putting the coin loop outside counts the 2 multisets and .
A process starts in state 0. Each step costs 1; from state it stays in with probability and moves to with probability ; it stops at . What is the expected number of steps?
Show the answer
C.
First-step analysis: . Solving for gives , so : each advance takes steps on average.
In a pile of stones, a move removes 1 or 2 stones, and whoever takes the last stone wins. For which does the player to move lose against best play?
- Every even
- Every with
- Every multiple of 3
- No : the first player can always win
Show the answer
C. Every multiple of 3
0 is losing (no move); 1 and 2 are winning (move to 0); 3 is losing, since both moves reach a winning position; and the pattern repeats. From a non-multiple of 3, taking stones leaves a multiple of 3; from a multiple of 3, every move leaves a non-multiple.
Ordered sums of 1s and 2s that total are counted by . What makes this recurrence exact?
- Each sum has exactly one last term, 1 or 2, so the two cases are disjoint and together cover every sum
- The answers turn out to be Fibonacci numbers
- The problem has optimal substructure
- The table is filled from left to right
Show the answer
A. Each sum has exactly one last term, 1 or 2, so the two cases are disjoint and together cover every sum
A counting DP is exact when its cases partition the objects: removing the last term maps the sums ending in 1 bijectively to sums of , and those ending in 2 to sums of . Overlapping cases would count some sums twice; a missing case would lose some.
Go deeper
- Combinatorics Modulo a Prime · Binomials, Lucas’s theorem, Catalan numbers and inclusion–exclusion.
- Digit DP · Counting the numbers up to N with a property, one digit at a time.
- Combinatorial Games & Sprague–Grundy · Winning positions, nim-sums and Grundy numbers.
Further reading
- A. Laaksonen, Competitive Programmer's Handbook (2018, free online), chapters 7 (dynamic programming), 22 (combinatorics), 24 (probability) and 25 (game theory).
- R. L. Graham, D. E. Knuth & O. Patashnik, Concrete Mathematics, 2nd ed. (Addison-Wesley, 1994).
- M. Mitzenmacher & E. Upfal, Probability and Computing, 2nd ed. (Cambridge, 2017): linearity of expectation and the coupon collector.
- The CSES Problem Set, whose dynamic programming section has counting problems to practice on.