← All Posts
Combinatorics · Counting· Part 8 of 9

Catalan Numbers: The Universal Counting Sequence

What Are Catalan Numbers?

The Catalan numbers form one of the most frequently occurring sequences in combinatorics. The first few values are:

C0=1,   C1=1,   C2=2,   C3=5,   C4=14,   C5=42,   C6=132,   C7=429,   …

They appear in an astonishing variety of counting problems — from the number of valid arrangements of parentheses to the number of full binary trees with n internal nodes. Eugène Charles Catalan studied them in the 1830s, but the sequence was known to Euler and even to Chinese mathematicians centuries earlier.

In competitive programming, Catalan numbers surface surprisingly often. Recognising that a problem is "secretly Catalan" can collapse a complex counting task into a single formula evaluation.

OEIS A000108. The Catalan sequence grows roughly as 4n / (n3/2 √π), so values get large very fast. Most CP problems ask for the answer modulo a prime.

The Closed-Form Formula

The n-th Catalan number has the elegant closed form:

Cn = C(2n, n) / (n + 1)

Equivalently, using the binomial coefficient directly:

Cn = (2n)! / ((n + 1)! · n!)

Another useful form is the difference of binomial coefficients:

Cn = C(2n, n) − C(2n, n + 1)

Why this matters in CP. The difference form C(2n, n) − C(2n, n+1) avoids division entirely, which is helpful when working modulo a composite number where modular inverse may not exist.

Proof sketch (ballot problem approach): Consider paths on a grid from (0,0) to (2n,0) using steps +1 (up) and −1 (down), never going below the x-axis. The total number of unrestricted paths is C(2n, n). The number of "bad" paths (those that dip below zero) is C(2n, n+1) by the reflection principle. Subtracting gives Cn = C(2n, n) − C(2n, n+1).

Classic Interpretations

The real beauty of Catalan numbers is the sheer variety of objects they count. Here are at least five classic interpretations, each worth understanding deeply.

1. Balanced Parentheses

Cn counts the number of ways to arrange n pairs of parentheses so that they are correctly matched. For example, with n = 3:

((()))   (()())   (())()   ()(())   ()()()

That gives C3 = 5. This is perhaps the most fundamental Catalan interpretation and maps directly to many CP problems — any time a problem reduces to "count valid sequences of two matching symbols," think Catalan.

2. Full Binary Trees

Cn is the number of distinct full binary trees (every internal node has exactly 2 children) with n internal nodes (and thus n + 1 leaves). Equivalently, it counts the number of distinct rooted binary trees with n + 1 leaves.

This interpretation is central in compiler theory (expression trees) and in problems involving recursive tree structures.

3. Triangulations of a Convex Polygon

Cn counts the number of ways to divide a convex polygon with n + 2 sides into triangles using non-crossing diagonals. For a pentagon (n = 3), there are exactly 5 triangulations.

This connects Catalan numbers to computational geometry problems. The classic "polygon triangulation" problem has a Catalan-number answer.

4. Dyck Paths

A Dyck path of length 2n is a lattice path from (0, 0) to (2n, 0) consisting of steps U = (1, 1) and D = (1, −1) that never goes below the x-axis. The number of such paths is Cn.

Dyck paths are the geometric visualization behind the ballot problem and the reflection principle proof of the Catalan formula.

5. Non-Crossing Partitions

Cn counts the number of non-crossing partitions of the set {1, 2, …, n}. A partition is non-crossing if, when we draw the elements on a circle and connect elements in the same block, no two connecting arcs cross.

For n = 4, there are C4 = 14 non-crossing partitions.

Other Interpretations (Quick List)

Tip: When you encounter a new counting problem in a contest, ask yourself: "Does this reduce to one of the standard Catalan interpretations?" If so, the answer is likely Cn or a product/sum involving Catalan numbers.

Recurrence Relation

Catalan numbers satisfy the recurrence:

Cn = ∑i=0n−1 Ci · Cn−1−i,   with C0 = 1

Intuition via balanced parentheses: Consider the first opening parenthesis. It must close at some position 2i + 1 (for i = 0, 1, …, n − 1). Inside it there are i pairs (counted by Ci), and after it there are n − 1 − i pairs (counted by Cn−1−i). Summing over all positions gives the recurrence.

Intuition via binary trees: Pick the structure of the left subtree (i nodes, counted by Ci) and the right subtree (n − 1 − i nodes, counted by Cn−1−i).

The recurrence runs in O(n2) time if we compute all values up to n. This is useful when the closed form is hard to evaluate (e.g., modulo a composite).

// O(n^2) DP for Catalan numbers mod p
const int MOD = 1e9 + 7;
long long catalan[5001];

void precompute(int n) {
    catalan[0] = 1;
    for (int i = 1; i <= n; i++) {
        catalan[i] = 0;
        for (int j = 0; j < i; j++) {
            catalan[i] = (catalan[i] + catalan[j] % MOD * catalan[i - 1 - j] % MOD) % MOD;
        }
    }
}
Watch out: The O(n2) DP is fine for n ≤ 5000 but too slow for large n. For n up to 106 or beyond, use the closed-form formula with modular inverse.

Generating Function

The ordinary generating function (OGF) for the Catalan numbers is:

C(x) = ∑n≥0 Cn xn

From the recurrence Cn = ∑ Ci Cn−1−i, we recognise a convolution, which means:

C(x) = 1 + x · C(x)2

Solving this quadratic in C(x):

C(x) = (1 − √(1 − 4x)) / (2x)

We take the minus sign in front of the square root because we need C(0) = C0 = 1 (the plus sign gives a series diverging at x = 0).

Deriving the closed form from the GF: Expanding √(1 − 4x) using the generalised binomial theorem gives:

√(1 − 4x) = ∑n≥0 C(1/2, n) (−4x)n

After simplification, the coefficient of xn in C(x) works out to C(2n, n) / (n + 1), confirming the closed form.

Advanced: The generating function is extremely useful for proving Catalan identities and for problems involving convolutions of Catalan sequences. In competitive programming, you rarely need the GF directly, but understanding it deepens your intuition.

Computing Catalan Numbers Efficiently

In competitive programming, we typically compute Cn modulo a large prime (usually 109 + 7). The key steps are:

  1. Precompute factorials and inverse factorials up to 2n.
  2. Compute C(2n, n) using precomputed values.
  3. Multiply by the modular inverse of (n + 1).
#include <bits/stdc++.h>
using namespace std;

const int MOD = 1e9 + 7;
const int MAXN = 2e6 + 5;
long long fac[MAXN], inv_fac[MAXN];

long long power(long long base, long long exp, long long mod) {
    long long result = 1;
    base %= mod;
    while (exp > 0) {
        if (exp & 1) result = result * base % mod;
        base = base * base % mod;
        exp >>= 1;
    }
    return result;
}

void precompute_factorials() {
    fac[0] = 1;
    for (int i = 1; i < MAXN; i++)
        fac[i] = fac[i - 1] * i % MOD;
    inv_fac[MAXN - 1] = power(fac[MAXN - 1], MOD - 2, MOD);
    for (int i = MAXN - 2; i >= 0; i--)
        inv_fac[i] = inv_fac[i + 1] * (i + 1) % MOD;
}

long long C(int n, int k) {
    if (k < 0 || k > n) return 0;
    return fac[n] % MOD * inv_fac[k] % MOD * inv_fac[n - k] % MOD;
}

long long catalan(int n) {
    // C_n = C(2n, n) / (n + 1)
    return C(2 * n, n) % MOD * power(n + 1, MOD - 2, MOD) % MOD;
}

// Alternative: C_n = C(2n, n) - C(2n, n+1) — no division needed
long long catalan_alt(int n) {
    return (C(2 * n, n) - C(2 * n, n + 1) + MOD) % MOD;
}

int main() {
    precompute_factorials();
    int n;
    cin >> n;
    cout << catalan(n) << "\n";
    return 0;
}
Complexity: O(N) precomputation, O(1) per query. This handles n up to 106 comfortably within time and memory limits.

Handling Composite Moduli

If the modulus is composite, modular inverse may not exist. In this case, use one of:

CP Applications

Counting Valid Bracket Sequences

Problem: Given n, count the number of valid sequences of n pairs of parentheses. Answer: Cn.

Generalisation: if we have multiple types of brackets (e.g., (), [], {}), the answer for k bracket types is kn · Cn.

Number of BST Shapes

Problem: Given n distinct keys, how many structurally distinct BSTs can be formed? Answer: Cn.

// Count distinct BSTs for n keys
// Simply compute catalan(n) using the function above
int main() {
    precompute_factorials();
    int n;
    cin >> n;
    cout << catalan(n) << "\n";
}

Grid Paths Below Diagonal

Problem: Count lattice paths from (0, 0) to (n, n) using steps right (R) and up (U) that never go above the diagonal y = x. Answer: Cn.

More generally, paths from (0, 0) to (m, n) with m ≥ n that stay weakly below y = x is given by the ballot-style formula:

(m − n + 1) / (m + 1) · C(m + n, n)

Polygon Triangulation

Problem: In how many ways can a convex polygon with n + 2 vertices be triangulated? Answer: Cn.

Stack-Sortable Permutations

Problem: How many permutations of {1, …, n} can be sorted by passing through a single stack? Answer: Cn.

Recognition tip: Whenever a problem involves nested structures, balanced sequences, or recursive decompositions where you split into a "left part" and "right part" at every level, suspect Catalan numbers.

Generalizations

The ballot problem generalises Catalan numbers. The number of sequences of p copies of +1 and q copies of −1 (with p ≥ q) whose partial sums are always non-negative is:

(p − q + 1) / (p + 1) · C(p + q, q)

Setting p = q = n recovers Cn.

Super Catalan (Schröder) numbers and Motzkin numbers are related sequences that count paths with additional step types.

Catalan Number Modulo Identities

Practice Problems

  1. Balanced Brackets — Given n, output Cn mod 109+7. (Direct application of the formula.)
  2. Distinct BSTs (LeetCode 96) — Count the number of structurally unique BSTs that store values 1 to n.
  3. Dyck Paths with Obstacles — Count Dyck paths of length 2n that avoid certain lattice points. (Requires inclusion-exclusion on top of Catalan.)
  4. Polygon Triangulation Counting — Given a convex polygon with n vertices, count the number of triangulations.
  5. CF 9D — How Many Trees? — Count binary trees with at most n vertices and height at most h.
  6. CF 1830C — Hyperregular Bracket Strings — Counting bracket sequences with constraints, reducible to products of Catalan numbers.
Summary: Catalan numbers Cn = C(2n, n) / (n+1) count an enormous family of combinatorial objects. The closed-form with modular inverse handles most CP settings; fall back to the O(n2) recurrence when the modulus is composite. Learn the classic interpretations — they are your pattern-matching toolkit for recognising Catalan problems in contests.