Catalan numbers

Also , which computes them in with one inverse per step.

What Catalan numbers count

ObjectCount
Balanced bracket sequences of length
Binary trees with internal nodes
Triangulations of a convex -gon
Monotone lattice paths below the diagonal
Ways to parenthesise factors
Non-crossing chord diagrams on points
Permutations avoiding any fixed 3-pattern
Standard Young tableaux of shape
Mountain ranges with up and down strokes

These are all the “same” object under bijection — recognising one lets you count all the others.

The reflection principle

Paths from to using right/up steps that never cross the diagonal:

The subtracted term counts the bad paths, put in bijection with unrestricted paths to by reflecting the portion after the first violation. This reflection argument generalises to the ballot problem and to paths with other boundary constraints — it is the technique, not the formula, that is worth learning.

Ballot problem: the number of paths from to with staying strictly above the diagonal is .

Stirling numbers

Second kind — partitions of labelled objects into non-empty unlabelled blocks:

The closed form is an inclusion-exclusion over which blocks are empty, computable in .

First kind (unsigned) — permutations of elements with exactly cycles:

Bell numbers — all set partitions of elements: (Catalan and Bell agree up to then diverge).

Surjections and derangements

Surjections from elements onto : .

Derangements — permutations with no fixed point:

Permutations with exactly fixed points: .

Other sequences worth recognising

SequenceCountsStart
Motzkin lattice paths with up/down/flat steps1,1,2,4,9,21,51
Narayana brackets with exactly peaks;
Schröderpaths with diagonal steps1,2,6,22,90
Eulerian permutations with descents
Fibonaccisee Fibonacci1,1,2,3,5,8
Partition integer partitions1,1,2,3,5,7,11
Delannoypaths with diagonal steps, unrestricted

Look it up

When a counting problem produces an unfamiliar sequence, compute the first 6-8 terms by brute force and search OEIS. It very often names the sequence, gives a closed form or recurrence, and links a proof. This is a legitimate and highly effective contest technique.

Computing modulo a prime

All of the above have or DP forms and -per-query closed forms once factorials and inverse factorials are precomputed. Watch for:

  • in the Catalan formula needs a modular inverse;
  • the inclusion-exclusion forms need alternating signs handled with (MOD - x) % MOD;
  • Stirling numbers for a whole row can be computed by one convolution in .

See also: Combinatorics · Generating Functions · Burnside and Pólya