Catalan numbers
The Catalan numbers count balanced bracket sequences, ordered binary trees, triangulations of convex polygons and several related structures. Their common property is a unique decomposition into one fixed piece and two independent smaller parts. We can calculate them using an O(n^2) recurrence or a binomial coefficient formula.
Balanced bracket sequences
Take 2 opening and 2 closing brackets. There are 6 ways to arrange them, and only 2 of them are balanced: (()) and ()(). To check an arrangement, read it from left to right and keep a running count: add 1 for ( and subtract 1 for ).
The arrangement is balanced when the count never drops below 0 and ends at 0. In ())( the count goes 1, 0, −1 and fails at the third bracket, a ) with no ( left to close.
Fig. 1. Of the 6 ways to arrange two ( and two ), 2 are balanced. Red marks the first bracket where the running count drops below 0.
With 3 pairs there are already 20 arrangements, with 10 pairs 184756, and problems ask about up to 10^6 pairs, so listing them is out. We want the count for 3 pairs from the counts for 1 and 2 pairs, and so on upwards.
Problems usually define a balanced sequence as empty, or a balanced sequence wrapped in a pair, or two shorter ones glued together. Counting 3 pairs this way, wrapping one of the 2 sequences of 2 pairs gives 2. Gluing 1 pair and then 2 pairs gives 1 · 2 = 2, and gluing 2 pairs and then 1 pair gives another 2.
That makes 6, but there are only 5 balanced sequences of 3 pairs: ()()() is made twice, once as () followed by ()() and once as ()() followed by ().
Fig. 2. Wrapping and gluing for 3 pairs. The two red rows are the same sequence.
A unique decomposition
Split each non-empty sequence at the closing bracket matching its first opening bracket.
Look at the first bracket. It is always (, and it has exactly one partner: the ) where the running count first comes back to 0. Everything between them is a balanced sequence; call it the inside part.
Between them the count stays at 1 or more and is 1 again just before the partner, so counted from 1 instead of 0, the inside part never goes below 0 and ends at 0. Everything after the partner is another balanced sequence, the after part. Either part can be empty.
Any inside part with any after part gives a balanced sequence, and different choices give different sequences, since every sequence has one first bracket and one partner.
With 3 pairs, the first pair takes one, so the inside and after parts share the other 2: 0 and 2, 1 and 1, or 2 and 0. That gives 1 · 2 + 1 · 1 + 2 · 1 = 5 sequences, and ()()() is counted once, with an empty inside part.
Fig. 3. Every sequence is split once, at the partner of its first bracket.
These counts are the Catalan numbers C_n. The empty sequence is the base case, C_0 = 1, and the split at the first pair is the transition: for n \ge 1,
where is the number of pairs inside the first pair. Filling them in order of , each from all the smaller ones, is dynamic programming.
Fig. 4 fills the table up to 5 pairs, one product at a time.
0 pairs: only the empty sequence, so 1.
Fig. 4. Step through the table with the buttons or the arrow keys. Each new cell (amber) is a sum of products of two blue cells.
The table also gives 14 sequences of 4 pairs and 42 of 5 pairs.
Binary trees and triangulations
Here a binary tree is a tree with a root in which every node has at most a left child and a right child, and a node with only a left child is different from one with only a right child.
A binary tree with nodes splits the same way as a sequence: the root, a left subtree with nodes and a right subtree with the other n - 1 - k. So there are C_n binary trees with nodes. Fig. 5 matches each of the 5 trees with 3 nodes to a balanced sequence.
Fig. 5. The root is the first pair, the left subtree is what is inside it, and the right subtree is what comes after.
The same split counts triangulations of a convex polygon with n + 2 corners. Take a hexagon with corners 1 to 6. The side 1–6 belongs to exactly one triangle; call its third corner . That triangle is the fixed piece, and the two smaller polygons on each side of it are cut into triangles independently.
For v = 2 the left side is empty (C_0 = 1) and the right side is the pentagon 2, 3, 4, 5, 6 (C_3 = 5), which gives 5. For v = 3 the left side is the triangle 1, 2, 3 (C_1 = 1) and the right side is the quadrilateral 3, 4, 5, 6 (C_2 = 2), which gives 1 · 2 = 2. The cases v = 4 and v = 5 are left.
Fig. 6. The triangle on side 1–6 is the fixed piece. The two polygons beside it are cut into triangles independently.
Handshakes split the same way. When people at a round table shake hands in pairs with no crossing arms, person 1 shakes hands with someone. That handshake is the fixed piece, and the people on each side of it shake hands only among themselves, so there are C_n ways.
Mountain paths and the formula
Draw a sequence as a path: one step up for each ( and one step down for each ). The height is the running count, so a balanced sequence is a mountain path (also called a Dyck path): it never goes below the ground and ends on it. The partner of the first bracket is where the path first comes back to the ground.
Fig. 7. The 5 mountain paths for 3 pairs. Blue marks the first pair: the first step up and the first return to the ground.
A path with steps up and down, with no rule about the ground, is a choice of which of the steps go up: there are \binom{2n}{n} of them, as in binomial coefficients. For 3 pairs that is 20. From these we subtract the bad paths, the ones that go below the ground.
Every step changes the height by 1, so a bad path has to touch the level one below the ground, the dashed line in Fig. 8. Take the first point where it does.
Mirror everything after that point, swapping steps up and down. The path used to end one level above the dashed line, so now it ends one level below it, two below the ground. A path that ends two below the ground has n - 1 steps up and n + 1 down.
The mirror also works backwards. A path that ends two below the ground has to touch the dashed line on its way down. Mirroring after its first touch brings the end back to the ground and gives a bad path, the same one we started from. So bad paths and paths ending two below the ground match one to one, and there are \binom{2n}{n+1} of those. For 3 pairs that is 15, and 20 - 15 = 5.
Fig. 8. Mirroring after the first touch of the dashed line works in both directions, so bad paths and paths ending two below the ground match one to one.
In general, C_n = \binom{2n}{n} - \binom{2n}{n+1}. Writing both with factorials, \binom{2n}{n+1} = \frac{(2n)!}{(n+1)!\,(n-1)!} = \frac{(2n)!}{n!\,n!}\cdot\frac{n}{n+1} = \binom{2n}{n} \cdot \frac{n}{n+1}, so this is the same as
Implementation
In code, C[i] is the number of balanced sequences of i pairs, and the table is filled with the stages of dynamic programming:
State:
C[i].Base case:
C[0] = 1, the empty sequence.Order:
ifrom 1 ton.Transition: for each
kfrom 0 toi - 1, add the sequences withkpairs inside the first pair andi - 1 - kafter it.Answer:
C[n].
C[36] no longer fits in long long, so problems ask for the answer modulo a number such as 10^9 + 7. The program reads one integer n, the number of pairs. For the run in Fig. 4 the input is:
5#include <iostream>
#include <vector>
using namespace std;
const long long MOD = 1000000007; // remove every % MOD for exact values (see the warning below)
int main() {
int n;
cin >> n;
vector<long long> C(n + 1, 0); // state
C[0] = 1; // base case
for (int i = 1; i <= n; i++) // order
for (int k = 0; k < i; k++) // transition
C[i] = (C[i] + C[k] * C[i - 1 - k]) % MOD;
cout << C[n] << "\n"; // answer
}The program only adds and multiplies, so MOD can be any number up to about 10^9, prime or not: each product stays below 10^{18}. It takes O(n^2) time and memory. For n = 10^4 that is about 5 \cdot 10^7 products; whether it fits depends on the time limit.
Large n modulo a prime
For n up to 10^6, use the formula from the mountain paths. The factorial implementation requires a prime modulus larger than MAXN, with MAXN >= 2 * n. For other moduli the recurrence is a straightforward alternative when the input size permits.
The functions power and binom(n, k) and the arrays fact and inv_fact come from binomial coefficients, renamed from C to binom so that C stays the Catalan number. The answer is binom(2 * n, n) - binom(2 * n, n + 1), and adding MOD keeps it from going negative.
#include <iostream>
#include <vector>
using namespace std;
const long long MOD = 1000000007; // a prime
const int MAXN = 2000000; // at least 2 * n: binom(2 * n, n) reads fact[2 * n]
long long power(long long x, long long n, long long m) {
long long result = 1 % m;
x %= m;
while (n > 0) {
if (n % 2 == 1) result = result * x % m;
x = x * x % m;
n /= 2;
}
return result;
}
vector<long long> fact(MAXN + 1), inv_fact(MAXN + 1);
long long binom(int n, int k) {
if (k < 0 || k > n) return 0;
return fact[n] * inv_fact[k] % MOD * inv_fact[n - k] % MOD;
}
int main() {
fact[0] = 1;
for (int i = 1; i <= MAXN; i++)
fact[i] = fact[i - 1] * i % MOD;
inv_fact[MAXN] = power(fact[MAXN], MOD - 2, MOD);
for (int i = MAXN; i > 0; i--)
inv_fact[i - 1] = inv_fact[i] * i % MOD;
int n;
cin >> n;
cout << (binom(2 * n, n) - binom(2 * n, n + 1) + MOD) % MOD << "\n"; // all paths minus the bad ones
}The factorials take time and memory whatever n is, so with many queries compute them once. Each answer then takes .
Common mistakes
Similar algorithms
Grid paths counts corner-to-corner paths in a grid. A mountain path is such a path that must not cross the diagonal, and that rule brings the count down from \binom{2n}{n} to C_n.
Backtracking lists the sequences one by one, so it works only for small : C_{20} is about 6.6 \cdot 10^9.
Interval DP handles splits whose pieces have costs, such as the cheapest triangulation of a polygon or the best way to bracket a product. It chooses the best split for each interval instead of counting them.
Practice
Orta (≈1350) · Combinatorics
Asan (≈1000) · Math
Orta (≈1350)
Asan (≈1000) · Dynamic programming · Math
Çox asan (≈850)
Asan (≈1000)
Çox asan (≈850)
Çətin (≈1650) · Dynamic programming · Trees