Simple Algorithm
Algorithms & Data Structures · Optimized · 22 min

Counting, Probability & Games

Dynamic programs that count, average, and decide who wins.

How many ways are there to tile a 2×1002 \times 100 board with dominoes? About 5.7×10205.7 \times 10^{20}, 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:

ways(s)=∑choices c at sways(the state after c).\text{ways}(s) = \sum_{\text{choices } c \text{ at } s} \text{ways}(\text{the state after } c).

The states, the fill order and the running time stay the same; only the operator changes.

Take tilings of a 2×n2 \times n board by 1×21 \times 2 dominoes, and look at the leftmost column. Either one vertical domino covers it, leaving a 2×(n−1)2 \times (n-1) board, or two horizontal dominoes cover the first two columns, leaving a 2×(n−2)2 \times (n-2) board. No tiling does both, and every tiling does one of them.

T(n)=T(n−1)+T(n−2),T(0)=T(1)=1T(n) = T(n-1) + T(n-2), \qquad T(0) = T(1) = 1
So T(n)T(n) is the Fibonacci number F(n+1)F(n+1): 1,1,2,3,5,8,…1, 1, 2, 3, 5, 8, \dots, and T(100)=F(101)≈5.7×1020T(100) = F(101) \approx 5.7 \times 10^{20}. T(0)=1T(0) = 1 because the empty board has exactly one tiling, the empty one.

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:

python
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]

Θ(RC)\Theta(RC) time for RR rows and CC columns. On a 3×33 \times 3 grid with no blocked cell it returns (42)=6\binom{4}{2} = 6. The count is reported modulo the prime 109+710^9 + 7 because counts grow exponentially; the next step gives the rules.

Think first Count the binary strings of length nn 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 n−1n-1 followed by 0. One ending in 1 must have a 0 before it, so it is any valid string of length n−2n-2 followed by 01. The two classes are disjoint and exhaustive, so f(n)=f(n−1)+f(n−2)f(n) = f(n-1) + f(n-2) with f(0)=1f(0) = 1 and f(1)=2f(1) = 2, which gives f(n)=F(n+2)f(n) = F(n+2): Fibonacci once more.

Count each object once

How many ways are there to pay 6 with coins of value 1, 3 and 4? If 1+1+41+1+4 and 4+1+14+1+1 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:

python
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 cc 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, ways[a]=∑cways[a−c]\text{ways}[a] = \sum_c \text{ways}[a - c] classifies payments by their last coin, so 1+1+41+1+4 and 4+1+14+1+1 are different. Both take Θ(kA)\Theta(kA) time for kk coins and amount AA.

Predict before you look

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 0,1,…,50, 1, \dots, 5: 6 ways. Counting orders instead gives 89, the stairs count F(11)F(11): 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 ss to state s′s' with probability P(s→s′)P(s \to s'), each step costing 1. Conditioning on the first step (the law of total expectation) gives

E[s]=1+∑s′P(s→s′) E[s′],E[s] = 1 + \sum_{s'} P(s \to s')\, E[s'],

with E=0E = 0 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.

python
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: E[s]E[s] is the expected number of further rolls, from total ss, until the total reaches nn. Θ(n)\Theta(n) time with six terms per state. For n=100n = 100 it returns about 29.0529.05, a little more than 100/3.5≈28.57100/3.5 \approx 28.57, 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 kk, the number of distinct faces seen so far. A roll that repeats an old face, with probability k/6k/6, leaves the state unchanged, so E[k]E[k] appears on both sides of its own equation. Guess first:

Predict before you look

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

6 (1+12+13+14+15+16)=6×2.45=14.76\,(1 + \tfrac12 + \tfrac13 + \tfrac14 + \tfrac15 + \tfrac16) = 6 \times 2.45 = 14.7, as the derivation below shows. The last new face alone takes 6 rolls on average.

DerivationSolving a self-loop: the coupon collector
  1. E[k]=1+k6 E[k]+6−k6 E[k+1]E[k] = 1 + \tfrac{k}{6}\,E[k] + \tfrac{6-k}{6}\,E[k+1]

    From state k<6k < 6, a roll shows an old face with probability k/6k/6 (stay) or a new one with probability (6−k)/6(6-k)/6 (move to k+1k+1):

  2. E[k]=66−k+E[k+1]E[k] = \frac{6}{6-k} + E[k+1]

    Move the self-loop term to the left and divide by (6−k)/6(6-k)/6:

  3. E[0]=6(16+15+14+13+12+1)=6H6=14.7E[0] = 6\left(\tfrac16 + \tfrac15 + \tfrac14 + \tfrac13 + \tfrac12 + 1\right) = 6H_6 = 14.7

    Unroll from E[6]=0E[6] = 0:

  4. E[0]=nHn=nln⁡n+O(n)E[0] = n H_n = n \ln n + O(n)

    With nn faces the same steps give nHn≈nln⁡nnH_n \approx n \ln n, where HnH_n is the nn-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 nn 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:

python
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 win

Θ(n ∣S∣)\Theta(n\,\abs{S}) time for the move set SS. The losing positions are 0,2,7,9,14,16,…0, 2, 7, 9, 14, 16, \dots: exactly the nn with n mod 7∈{0,2}n \bmod 7 \in \{0, 2\}. Periodicity is no accident: the Optimal lesson on games proves that every finite subtraction game becomes periodic.

nn0123456789
outcomeLWLWWWWLWL
a winning movenonetake 1nonetake 1take 4take 3take 4nonetake 1none
Moves {1,3,4}\{1, 3, 4\}. W: the player to move wins with best play; L: loses. A winning move leads to an L position.
Check your understanding

With the moves {1,3,4}\{1, 3, 4\}, it is your turn and the pile holds 10 stones. Which moves guarantee you a win?

  1. Taking 1 or taking 3
  2. Only taking 4
  3. Only taking 1
  4. None: 10 is a losing position
Show the answer

A. Taking 1 or taking 3

10−1=910 - 1 = 9 and 10−3=710 - 3 = 7 are both losing positions (9 mod 7=29 \bmod 7 = 2 and 7 mod 7=07 \bmod 7 = 0), 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 best(i,j)\text{best}(i, j) be the largest margin (own total minus the opponent's) that the player to move can guarantee on the coins a[i..j]a[i..j], inclusive. Taking the left coin gains a[i]a[i] and hands the opponent a[i+1..j]a[i+1..j], so

best(i,j)=max⁡(a[i]−best(i+1,j), a[j]−best(i,j−1)),\text{best}(i, j) = \max\big(a[i] - \text{best}(i+1, j),\ a[j] - \text{best}(i, j-1)\big),

an interval DP with n(n+1)/2n(n+1)/2 states and Θ(n2)\Theta(n^2) time.

The tree has 2n−12^{n-1} 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 239≈5.5×10112^{39} \approx 5.5 \times 10^{11} 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 109+710^9 + 7": 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 10810^8 simple operations per second in a compiled language).
Problem (in brief)State and transitionKey ideaCost
Tilings of a 2×n2 \times n board, or ways to climb nn stairs by 1 or 2, modulo a primeT(n)=T(n−1)+T(n−2)T(n) = T(n-1) + T(n-2)classify by the first pieceO(n)O(n); O(log⁡n)O(\log n) by matrix powers
Ways to pay an amount, order irrelevantways[a]+=ways[a−c]\text{ways}[a] \mathrel{+}= \text{ways}[a - c], coins outsidebuild each multiset in coin orderO(kA)O(kA)
Lattice paths avoiding blocked cellsways[r][c]=\text{ways}[r][c] = up ++ leftclassify by the last stepO(RC)O(RC)
Expected rolls to reach a total, or to see every faceE[s]=1+∑P E[s′]E[s] = 1 + \sum P\,E[s'], backwardfirst-step analysis; solve the self-loopsO(6n)O(6n)
Who wins a subtraction game, or coins in a lineW/L over nn; best(i,j)\text{best}(i, j) over intervalswinning iff some move reaches a losing positionO(n ∣S∣)O(n\,\abs{S}); O(n2)O(n^2)
A look-alike that does not fit: counting the simple paths between two vertices of a general graph. It sounds like path counting, but a simple path must not revisit a vertex, so the state would have to remember the set of vertices visited. Counting ss–tt simple paths is #P-complete (Valiant, 1979), so no polynomial-time algorithm is expected. Counting walks of length kk, which may revisit vertices, is easy: kk rounds of a table over the vertices, or a matrix power.

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, E[s]=1+∑s′P(s→s′) E[s′]E[s] = 1 + \sum_{s'} P(s \to s')\,E[s'], filled backward; a self-loop is removed by solving for E[s]E[s], 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.

Question 1

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 {1,2}\{1, 2\} and amount 3?

  1. 2
  2. 3
  3. 4
  4. 1
Show the answer

B. 3

With the amounts outside, the code classifies payments by their last coin, so it counts ordered sequences: 1+1+11{+}1{+}1, 1+21{+}2 and 2+12{+}1. Putting the coin loop outside counts the 2 multisets {1,1,1}\{1, 1, 1\} and {1,2}\{1, 2\}.

Question 2

A process starts in state 0. Each step costs 1; from state s<ns < n it stays in ss with probability 1/31/3 and moves to s+1s + 1 with probability 2/32/3; it stops at nn. What is the expected number of steps?

  1. nn
  2. 2n/32n/3
  3. 1.5 n1.5\,n
  4. 3n3n
Show the answer

C. 1.5 n1.5\,n

First-step analysis: E[s]=1+13E[s]+23E[s+1]E[s] = 1 + \tfrac13 E[s] + \tfrac23 E[s+1]. Solving for E[s]E[s] gives E[s]=32+E[s+1]E[s] = \tfrac32 + E[s+1], so E[0]=1.5 nE[0] = 1.5\,n: each advance takes 1/(2/3)=1.51/(2/3) = 1.5 steps on average.

Question 3

In a pile of nn stones, a move removes 1 or 2 stones, and whoever takes the last stone wins. For which nn does the player to move lose against best play?

  1. Every even nn
  2. Every nn with n mod 3=1n \bmod 3 = 1
  3. Every multiple of 3
  4. No nn: 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 n mod 3n \bmod 3 stones leaves a multiple of 3; from a multiple of 3, every move leaves a non-multiple.

Question 4

Ordered sums of 1s and 2s that total nn are counted by ways[n]=ways[n−1]+ways[n−2]\text{ways}[n] = \text{ways}[n-1] + \text{ways}[n-2]. What makes this recurrence exact?

  1. Each sum has exactly one last term, 1 or 2, so the two cases are disjoint and together cover every sum
  2. The answers turn out to be Fibonacci numbers
  3. The problem has optimal substructure
  4. 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 n−1n-1, and those ending in 2 to sums of n−2n-2. Overlapping cases would count some sums twice; a missing case would lose some.

Go deeper

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.