progress

~/dynamic-programming/catalan

Catalan numbers

Count balanced brackets and tree shapes: the numbers 1, 1, 2, 5, 14, 42, and the mirror trick that explains their formula.

what

The number of balanced strings with n pairs of brackets is C(2n, n) / (n + 1). The same numbers count binary tree shapes and many other things.

use when

You must count (not list) balanced brackets, tree shapes or non-crossing pairings, or pick one of them fairly at random.

time

O(n²) with the recurrence, O(n) with the formula

space

O(n)

You’ll recognise it when

  • You must count balanced bracket strings, binary tree shapes or ways to cut a polygon into triangles. Count them, not list them.
  • The small answers come out as 1, 1, 2, 5, 14, 42.
  • One choice splits the problem into two smaller copies that don’t affect each other: a first bracket and its partner, or a root and its two subtrees.
  • You need the k-th balanced string, or a fair random one, without building them all.

Don’t confuse it with counting every order of the brackets. That is C(2n, n), and it includes the strings that aren’t balanced.

The idea

Imagine walking on a beach, right at the edge of the sea. Every ( is one step up the sand. Every ) is one step down, towards the water. A string of brackets is a walk.

A string is balanced when the walk never goes into the water and finishes back at the edge. (()) goes up, up, down, down: dry all the way. ())( goes up, down, down: wet feet on the third step.

Now the question: with n ups and n downs, how many walks stay dry? Counting those directly is hard, because “stay dry” is a rule you must check at every step. Counting all the walks is easy. So count the wet ones and take them away. The mirror trick below turns every wet walk into a walk with no rule at all, and those are easy to count too.

How it works

Take one unbalanced string and follow what the trick does to it.

Scroll through the steps and the graphic follows along. You can also press play, step with the arrow keys, or edit the brackets and try your own.

  1. Turn the string into a walk. ( is a step up, ) is a step down, and you start at height 0.
  2. Follow it one bracket at a time. A balanced string never goes below 0, and ends at 0.
  3. Stop at the first step that lands on −1. That is the first wet step, and it proves the string is not balanced.
  4. Left alone, the rest of the walk ends at 0. Every walk with n ups and n downs ends there.
  5. Lay a mirror along the line at −1. Everything before the wet step stays as it is.
  6. Flip every step after it. Each up becomes a down, and each down becomes an up.
  7. The flipped walk ends at −2, whatever the string was. Ending 2 below the start takes 2 more downs than ups, so its 2n steps are n − 1 ups and n + 1 downs.
  8. Flip the same part again and the original comes back. So each unbalanced walk has exactly one partner.
  9. Count the partners instead. They are every order of n − 1 ups and n + 1 downs, with no rule to obey.
loading catalan…

Where the n − 1 and n + 1 come from, counted through the flip: the part before the mirror stops the first time the height is −1, so it has one more down than up. The part after it climbs from −1 back to 0, so it has one more up than down. Flipping that part swaps its ups and downs, which makes it one more down than up as well. Two extra downs in total.

Why it’s correct: think of two piles of cards. One pile holds the unbalanced walks. The other holds every walk that ends at −2. The flip gives each card in the first pile exactly one card in the second, and flipping back gives each card in the second exactly one in the first. Nothing is left over on either side, so the piles are the same size.

See every walk at once

One walk shows how the flip works. To believe the count, look at all of them together. Here are the six walks for two pairs. Press play and watch each unbalanced one find its partner. Then edit pairs to 3: twenty walks, fifteen partners, five left dry.

loading catalan-pairs…

That gives the formula:

balanced = all walks − unbalanced walks
= C(2n, n) − C(2n, n + 1)
= C(2n, n) / (n + 1)

C(2n, n) means “the number of ways to choose which n of the 2n steps are ups”.

pairs n all walks unbalanced balanced
1 2 1 1
2 6 4 2
3 20 15 5
4 70 56 14
5 252 210 42

Counting from the middle of a string

The trick also works when part of the string is already written. Say there are opens_left ups and closes_left downs still to place. The walk starts higher up the beach, the mirror is still at −1, and the same flip gives:

ways to finish = C(total, closes_left) − C(total, closes_left + 1) total = opens_left + closes_left

That count is what lets you build one string without building them all. To make the k-th string in dictionary order, look at each position in turn. Count how many balanced strings have ( there. If k is smaller than that, write (. If not, skip those strings: take that count away from k and write ).

It is also how you pick a fair random string: choose k at random from 0 to the Catalan number minus one, then build the k-th string. Tossing a coin at each step is not fair. For three pairs, the coin gives ((())) one time in four, and a fair pick gives it one time in five.

from math import comb
def catalan(n):
"""How many balanced strings have n pairs of brackets."""
ways = [1] + [0] * n # ways[0]: the empty string
for m in range(1, n + 1):
# The first "(" closes somewhere: i pairs sit inside it, m - 1 - i come after.
ways[m] = sum(ways[i] * ways[m - 1 - i] for i in range(m))
return ways[n]
def completions(opens_left, closes_left):
"""How many ways to finish a balanced string with this many brackets still to place."""
total = opens_left + closes_left
# Every order of what's left, minus the orders that dip below zero (the mirror trick).
return comb(total, closes_left) - comb(total, closes_left + 1)
def kth_balanced(n, k):
"""The k-th balanced string with n pairs (k from 0), in dictionary order with "(" first."""
out = []
opens_left, closes_left = n, n
while opens_left + closes_left > 0:
with_open = completions(opens_left - 1, closes_left) if opens_left > 0 else 0
if k < with_open: # the string we want has "(" here
out.append("(")
opens_left -= 1
else: # skip every string that has "(" here
k -= with_open
out.append(")")
closes_left -= 1
return "".join(out)
#include <bits/stdc++.h>
using namespace std;
// How many balanced strings have n pairs of brackets. Fits in 64 bits up to n = 35.
long long catalan(int n) {
vector<long long> ways(n + 1, 0);
ways[0] = 1; // the empty string
for (int m = 1; m <= n; m++) {
// The first "(" closes somewhere: i pairs sit inside it, m - 1 - i come after.
for (int i = 0; i < m; i++) ways[m] += ways[i] * ways[m - 1 - i];
}
return ways[n];
}
// "n choose k": how many ways to pick k of n things.
long long choose(int n, int k) {
if (k < 0 || k > n) return 0;
k = min(k, n - k);
long long r = 1;
for (int i = 0; i < k; i++) r = r * (n - i) / (i + 1);
return r;
}
// How many ways to finish a balanced string with this many brackets still to place.
long long completions(int opensLeft, int closesLeft) {
int total = opensLeft + closesLeft;
// Every order of what's left, minus the orders that dip below zero (the mirror trick).
return choose(total, closesLeft) - choose(total, closesLeft + 1);
}
// The k-th balanced string with n pairs (k from 0), in dictionary order with "(" first.
string kthBalanced(int n, long long k) {
string out;
int opensLeft = n, closesLeft = n;
while (opensLeft + closesLeft > 0) {
long long withOpen = opensLeft > 0 ? completions(opensLeft - 1, closesLeft) : 0;
if (k < withOpen) { // the string we want has "(" here
out += '(';
opensLeft--;
} else { // skip every string that has "(" here
k -= withOpen;
out += ')';
closesLeft--;
}
}
return out;
}
import java.util.*;
class Catalan {
// How many balanced strings have n pairs of brackets. Fits in a long up to n = 35.
static long catalan(int n) {
long[] ways = new long[n + 1];
ways[0] = 1; // the empty string
for (int m = 1; m <= n; m++) {
// The first "(" closes somewhere: i pairs sit inside it, m - 1 - i come after.
for (int i = 0; i < m; i++) ways[m] += ways[i] * ways[m - 1 - i];
}
return ways[n];
}
// "n choose k": how many ways to pick k of n things.
static long choose(int n, int k) {
if (k < 0 || k > n) return 0;
k = Math.min(k, n - k);
long r = 1;
for (int i = 0; i < k; i++) r = r * (n - i) / (i + 1);
return r;
}
// How many ways to finish a balanced string with this many brackets still to place.
static long completions(int opensLeft, int closesLeft) {
int total = opensLeft + closesLeft;
// Every order of what's left, minus the orders that dip below zero (the mirror trick).
return choose(total, closesLeft) - choose(total, closesLeft + 1);
}
// The k-th balanced string with n pairs (k from 0), in dictionary order with "(" first.
static String kthBalanced(int n, long k) {
StringBuilder out = new StringBuilder();
int opensLeft = n, closesLeft = n;
while (opensLeft + closesLeft > 0) {
long withOpen = opensLeft > 0 ? completions(opensLeft - 1, closesLeft) : 0;
if (k < withOpen) { // the string we want has "(" here
out.append('(');
opensLeft--;
} else { // skip every string that has "(" here
k -= withOpen;
out.append(')');
closesLeft--;
}
}
return out.toString();
}
}

catalan uses the recurrence, which is the version to write when you’ve never seen the formula: the first ( closes somewhere, with i pairs inside it and m − 1 − i after it. completions is the mirror trick as one line. kth_balanced uses it once per bracket.

Why it’s O(n²) or better

The recurrence fills n entries, and entry m adds up m products: about n² / 2 multiplications, in O(n) space. The formula needs one binomial, which is O(n) multiplications. kth_balanced places 2n brackets and computes two binomials for each.

Listing the strings is hopeless long before that, because the numbers grow about four times bigger with each extra pair:

pairs n balanced strings
5 42
10 16,796
20 6,564,120,420
35 about 3.1 × 10¹⁸, the last one that fits in 64 bits

Common mistakes

Starting the table at 0

There is exactly one way to write a balanced string with no brackets: the empty string. If ways[0] is 0, every product in the sum is 0 and so is every answer.

ways = [0] * (n + 1) # ✗ everything stays 0
ways = [1] + [0] * n # ✓ the empty string counts as one way

Dividing with /

In Python, / gives a float, and a float holds only about 16 digits. The answer for 40 pairs has 22.

comb(2 * n, n) / (n + 1) # ✗ a float: wrong digits once the answer passes 2⁵³
comb(2 * n, n) // (n + 1) # ✓ exact, and the division never leaves a remainder

Tossing a coin for a random string

Choosing ( or ) with equal chance whenever both are allowed looks fair, but it favours strings with few choices along the way. Weight each choice by how many balanced strings lie behind it, or pick k at random and build the k-th string.

Overflow in C++ and Java

The Catalan number for 36 pairs no longer fits in a signed 64-bit integer. Past 35, use a big-integer type, or work modulo a prime if the problem asks for that.

Variations

  • Binary search trees. The number of tree shapes with n nodes is the same number. The root plays the first bracket: i nodes go left and n − 1 − i go right.
  • Triangulating a polygon. A polygon with n + 2 sides can be cut into triangles in the same number of ways. Fix one side: the triangle on it splits the rest into two smaller polygons.
  • Handshakes that don’t cross. 2n people round a table shake hands in pairs with no arms crossing. Person 1’s partner splits the table into two independent groups.
  • Ballot numbers. “Candidate A is never behind during the count” is the same walk. The count from the middle of a string, above, is this version.
  • Answers modulo a prime. For large n, use the formula with factorials and modular inverses, or the recurrence with every sum reduced as you go.

Check yourself

5 quick questions. Pick an answer to see why it's right or wrong.

  1. 1

    How many different binary search trees can hold the keys 1 to n, for n up to 30? You only need the count.

  2. 2

    What does this print?

    ways = [1, 0, 0, 0, 0]
    for m in range(1, 5):
    ways[m] = sum(ways[i] * ways[m - 1 - i] for i in range(m))
    print(ways[4])
  3. 3

    A walk has 4 ups and 4 downs and goes below 0 at some point. You flip every step after its first step at −1. Where does the flipped walk end?

  4. 4

    This is meant to return the exact Catalan number. What’s wrong with it?

    from math import comb
    def catalan(n):
    return comb(2 * n, n) / (n + 1)
  5. 5

    To make a random balanced string with 3 pairs, you add ( or ) with a fair coin whenever both are allowed, and take the only legal bracket otherwise. How likely is ((()))?

Practice problems

Solve these right here, in Python, C++ or Java. Tests run as you go.

Further reading

esc