Skip to content
LeetQuant
F2 Counting and Combinatorics

F2 · Counting and Combinatorics · Lesson 3 of 4

Recursive Counting

Setting up recurrences by conditioning on the first or last step, Catalan numbers through Dyck paths and the ballot theorem, and solving linear recurrences in closed form.

20 min

Condition on the last step

When a direct formula is not obvious, let ana_n be the answer for size nn and ask: how can a valid object of size nn end? Each way of ending leaves a smaller valid object, and the cases must be disjoint and exhaustive. That gives a recurrence; small cases give the initial conditions.

Tilings. Tile a 1×n1 \times n strip with 1×11 \times 1 squares and 1×21 \times 2 dominoes. The last tile is a square (leaving n−1n - 1) or a domino (leaving n−2n - 2), so tn=tn−1+tn−2t_n = t_{n-1} + t_{n-2} with t0=t1=1t_0 = t_1 = 1. These are Fibonacci numbers: tn=Fn+1t_n = F_{n+1} with F1=F2=1F_1 = F_2 = 1. The same recurrence counts domino tilings of a 2×n2 \times n board (the last column is one vertical domino, or the last two columns are two horizontal ones) and ways to climb nn stairs taking 1 or 2 steps at a time.

Binary strings with no two consecutive 1s. A valid string of length nn ends in 0 (anything valid of length n−1n - 1 before it) or in 01 (anything valid of length n−2n - 2 before it). So bn=bn−1+bn−2b_n = b_{n-1} + b_{n-2} with b1=2b_1 = 2, b2=3b_2 = 3, giving bn=Fn+2b_n = F_{n+2}: 2,3,5,8,13,…2, 3, 5, 8, 13, \dots, and b10=144b_{10} = 144.

The common mistake is cases that overlap or miss something. "Ends in 0" and "ends in 1" are exhaustive, but "ends in 1" is not a free choice, which is why you expand it to "ends in 01".

Worked example

no two heads in a row

You flip a fair coin 10 times. What is the probability that no two consecutive flips are both heads? How fast does this probability decay with nn?

Show solution

Map H to 1 and T to 0. The good sequences are the binary strings of length 10 with no "11", and b10=F12=144b_{10} = F_{12} = 144. So

P=144210=1441024=964≈0.141.P = \frac{144}{2^{10}} = \frac{144}{1024} = \frac{9}{64} \approx 0.141 .

For the decay rate, Fn≈φn/5F_n \approx \varphi^n / \sqrt5 with φ=1+52≈1.618\varphi = \tfrac{1 + \sqrt5}{2} \approx 1.618, so Pn≈c (φ/2)n=c⋅0.809nP_n \approx c\,(\varphi/2)^n = c \cdot 0.809^n. Each extra flip multiplies the probability by about 0.81, not by the naive 34\tfrac34 you might guess from "each new pair is HH with probability 14\tfrac14". The pairs overlap, so they are not independent.

A state-based version of the same count: let xnx_n, yny_n be the number of good strings ending in 0 and in 1. Then xn=xn−1+yn−1x_n = x_{n-1} + y_{n-1} and yn=xn−1y_n = x_{n-1}, which is the code below.

Recurrences in code

The state version is the safest way to code these counts, and it generalises to any "forbidden pattern" problem: the state is how much of the pattern you have just seen.

from functools import lru_cache

def no_consecutive_ones(n: int) -> int:
    # end0, end1: valid strings of the current length ending in 0 / in 1
    end0, end1 = 1, 1  # length 1: "0", "1"
    for _ in range(n - 1):
        end0, end1 = end0 + end1, end0
    return end0 + end1

@lru_cache(maxsize=None)
def catalan(n: int) -> int:
    # first-return decomposition: C_n = sum_i C_i * C_{n-1-i}
    if n == 0:
        return 1
    return sum(catalan(i) * catalan(n - 1 - i) for i in range(n))

print([no_consecutive_ones(n) for n in range(1, 11)])
print([catalan(n) for n in range(10)])

Output:

[2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
[1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862]

Catalan numbers and Dyck paths

A Dyck path of length 2n2n is a sequence of nn up-steps (+1)(+1) and nn down-steps (−1)(-1) whose running sum never goes below 0. Balanced strings of nn pairs of brackets, ways to fully parenthesise a product of n+1n + 1 factors, and triangulations of a convex (n+2)(n+2)-gon are all in bijection with them. Their count is the Catalan number CnC_n.

Recurrence (first return). A non-empty Dyck path first returns to 0 at step 2(i+1)2(i+1) for some i∈{0,…,n−1}i \in \{0, \dots, n-1\}. Before that it is "up, a Dyck path of length 2i2i, down"; after it, any Dyck path of length 2(n−1−i)2(n - 1 - i). So

Cn=∑i=0n−1Ci Cn−1−i,C0=1.C_n = \sum_{i=0}^{n-1} C_i\, C_{n-1-i}, \qquad C_0 = 1 .

Closed form (reflection). Of the (2nn)\binom{2n}{n} paths from 0 to 0, call a path bad if it ever reaches −1-1. Reflect a bad path after its first visit to −1-1 (swap every later up and down). It now ends at −2-2, and every path to −2-2 arises exactly once this way. Paths to −2-2 have n−1n - 1 ups and n+1n + 1 downs, so

Cn=(2nn)−(2nn−1)=1n+1(2nn).C_n = \binom{2n}{n} - \binom{2n}{n-1} = \frac{1}{n+1}\binom{2n}{n} .

The sequence is 1,1,2,5,14,42,132,429,…1, 1, 2, 5, 14, 42, 132, 429, \dots. Recognising 1,2,5,141, 2, 5, 14 in small cases is often how you spot a Catalan problem in an interview.

The ballot theorem

In an election, A gets aa votes and B gets b<ab < a, counted in a uniformly random order. The probability that A is strictly ahead throughout the count is

P=a−ba+b.P = \frac{a - b}{a + b} .

Proof by reflection: the first vote must be for A, so count paths from height 1 at step 1 to height a−ba - b at step a+ba + b that never touch 0. All such paths number (a+b−1a−1)\binom{a+b-1}{a-1}. Those that do touch 0 reflect (up to the first touch) into paths starting at −1-1, of which there are (a+b−1a)\binom{a+b-1}{a}. Dividing the difference by (a+ba)\binom{a+b}{a} gives aa+b−ba+b\tfrac{a}{a+b} - \tfrac{b}{a+b}.

Worked example

a 6–4 election

A wins an election 6 votes to 4. The ballots are counted in a random order. What is the probability that A is strictly ahead after every ballot? Check it by counting paths.

Show solution

The ballot theorem gives 6−46+4=15\frac{6 - 4}{6 + 4} = \frac15.

By counting: there are (104)=210\binom{10}{4} = 210 orders. The first ballot must be for A. From there, paths from height 1 to height 2 over the remaining 9 ballots number (95)=126\binom95 = 126 (5 more A votes among 9). The ones that touch 0 reflect to paths from −1-1 to 22, which need 6 ups among 9: (96)=84\binom96 = 84. So the good count is 126−84=42126 - 84 = 42, and 42/210=1542 / 210 = \tfrac15.

A quick interview corollary: with a=n+1a = n + 1, b=nb = n, the probability is 12n+1\tfrac{1}{2n+1}. Multiplying by (2n+1n)\binom{2n+1}{n} gives 12n+1(2n+1n)=Cn\tfrac{1}{2n+1}\binom{2n+1}{n} = C_n, which is another way to see the Catalan formula.

Solving linear recurrences

A homogeneous linear recurrence with constant coefficients,

an=c1an−1+c2an−2+⋯+cdan−d,a_n = c_1 a_{n-1} + c_2 a_{n-2} + \cdots + c_d a_{n-d},

is solved by trying an=rna_n = r^n. This gives the characteristic equation rd=c1rd−1+⋯+cdr^d = c_1 r^{d-1} + \cdots + c_d.

  • Distinct roots r1,…,rdr_1, \dots, r_d: an=∑iαirina_n = \sum_i \alpha_i r_i^n, with the αi\alpha_i fixed by the dd initial values.
  • A root rr of multiplicity mm contributes (β0+β1n+⋯+βm−1nm−1)rn(\beta_0 + \beta_1 n + \cdots + \beta_{m-1} n^{m-1}) r^n.
  • Inhomogeneous an=(linear part)+g(n)a_n = (\text{linear part}) + g(n): add one particular solution to the general homogeneous solution. For a polynomial gg, try a polynomial of the same degree, raised by one degree for each time 1 is a root of the characteristic equation.

Fibonacci: r2=r+1r^2 = r + 1 has roots φ,ψ=1±52\varphi, \psi = \tfrac{1 \pm \sqrt5}{2}, and F1=F2=1F_1 = F_2 = 1 give Binet's formula Fn=(φn−ψn)/5F_n = (\varphi^n - \psi^n)/\sqrt5. Since ∣ψ∣<1|\psi| < 1, FnF_n is the nearest integer to φn/5\varphi^n / \sqrt5.

The asymptotic growth is set by the largest root, which is often all an interviewer wants: "the count grows like φn\varphi^n".

Worked example

two recurrences solved

(a) Solve an=5an−1−6an−2a_n = 5a_{n-1} - 6a_{n-2} with a0=0a_0 = 0, a1=1a_1 = 1.

(b) nn straight lines are drawn in the plane, no two parallel and no three through one point. Find the number of regions RnR_n.

Show solution

(a) The characteristic equation is r2−5r+6=0r^2 - 5r + 6 = 0, so r=2,3r = 2, 3 and an=α2n+β3na_n = \alpha 2^n + \beta 3^n. From a0=0a_0 = 0: α=−β\alpha = -\beta. From a1=1a_1 = 1: 3β−2β=13\beta - 2\beta = 1, so β=1\beta = 1 and

an=3n−2n.a_n = 3^n - 2^n .

Check: a2=5⋅1−0=5=9−4a_2 = 5 \cdot 1 - 0 = 5 = 9 - 4, and a3=25−6=19=27−8a_3 = 25 - 6 = 19 = 27 - 8.

(b) Condition on the last line. It crosses each of the other n−1n - 1 lines exactly once, at distinct points, so it passes through nn existing regions and splits each in two:

Rn=Rn−1+n,R0=1.R_n = R_{n-1} + n, \qquad R_0 = 1 .

The characteristic root is 1, so for g(n)=ng(n) = n try a quadratic. Summing directly is easier: Rn=1+∑k=1nk=n(n+1)2+1R_n = 1 + \sum_{k=1}^n k = \frac{n(n+1)}{2} + 1. So 10 lines give 56 regions (the pizza-cutting puzzle), and 6 give 22.

Knowledge check

In how many ways can a 2 × 8 board be tiled with 1 × 2 dominoes?

Knowledge check

How many sequences of 5 opening and 5 closing brackets are balanced (every prefix has at least as many openings as closings)?

Knowledge check

Solve an=4an−1−4an−2a_n = 4a_{n-1} - 4a_{n-2} with a0=1a_0 = 1, a1=4a_1 = 4.

Key takeaways

  • Set up a recurrence by asking how a valid object of size nn can end (or start). Make the cases disjoint and exhaustive.
  • Tilings with pieces of size 1 and 2, stair climbing, and binary strings with no "11" are all Fibonacci; count with states when the constraint is a forbidden pattern.
  • Catalan numbers Cn=1n+1(2nn)C_n = \frac{1}{n+1}\binom{2n}{n} count Dyck paths and balanced brackets; derive them by first return (recurrence) or by reflection (closed form).
  • Ballot theorem: A strictly ahead throughout with probability a−ba+b\frac{a-b}{a+b}.
  • Linear recurrences: roots of the characteristic equation, njrnn^j r^n terms for repeated roots, plus a particular solution for an inhomogeneous term. The largest root sets the growth rate.

Practice problems

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).