AdvancedMath for DSADynamic Programming

Catalan numbers: 1, 1, 2, 5, 14, 42…

Valid bracket strings, distinct BSTs, polygon triangulations: all Catalan numbers. Spot it and a hard count becomes a formula.

The idea

Cₙ counts structures that split into a left part and a right part around a : pick what goes first (the root, the matching pair), then the two sides are independent. That gives Cₙ = Σ Cᵢ · Cₙ₋₁₋ᵢ, with C₀ = 1.

Closed form: Cₙ = C(2n, n) / (n + 1). The sequence grows fast (about 4ⁿ), so generating all of them is even if counting is cheap.

Worked example

How many BSTs hold the values 1, 2, 3?

  1. Root 1: left has 0 values, right has 2 → C₀ · C₂ = 1 · 2 = 2
  2. Root 2: 1 value each side → C₁ · C₁ = 1
  3. Root 3: 2 left, 0 right → 2. Total 5 = C₃.

Pseudocode

The steps in plain words. ← means “set to”; indentation shows what's inside what.

catalan[0] ← 1
for nodes from 1 to n:
for left from 0 to nodes − 1:(left subtree size)
right ← nodes − 1 − left
catalan[nodes] ← catalan[nodes] + catalan[left] × catalan[right]
return catalan[n]

See it run

The worked example, step by step, beside the Python. The highlighted line is the one running.

Step-by-step

values 1…3

catalan

01
10
20
30

Solution · Pythonline 2

def num_trees(n):
catalan = [1] + [0] * n
for nodes in range(1, n + 1):
for left in range(nodes): # left subtree size
catalan[nodes] += catalan[left] * catalan[nodes - 1 - left]
return catalan[n] # num_trees(3) == 5

Step 1 of 5· line 2

catalan[k] = how many BST shapes k values make. An empty tree is 1 shape. For k values, try each as the root: (shapes of the left side) × (shapes of the right side).

with the , with the closed form.

How to spot it

  • “how many structurally different trees / valid bracket strings / ways to split”, answers 1, 2, 5, 14 for small n.

Common mistakes

  • Trying to generate every structure just to count them.
  • Off by one: C₃ counts 3 or 3 pairs of brackets.

Practise the ideas first

Where it comes up

Go further