DrawCode Algorithm Visualizer • Dynamic Programming • Medium

Catalan Number

Tags: DP, Combinatorics, Catalan, BST

1. One-Liner

The n-th Catalan number counts dozens of equivalent structures (balanced parentheses, binary trees, polygon triangulations) and satisfies C_n = Σ C_i·C_{n-1-i} with DP in O() or closed form.


2. The Problem It Solves

You need the number of well-formed length-2n parenthesis strings, or full binary trees with n+1 leaves, etc.—all counted by Catalan numbers.


3. The Core Idea

First split decomposition: choose where the matching closing paren pairs with the first open—left and right subproblems are independent smaller Catalan instances → convolution recurrence.


4. How It Works (Step-by-Step)

StepWhat Happens
1C0=1
2C_n = Σ_{i=0}^{n-1} C_i·C_{n-1-i}
3Fill 0..n increasing
4Optional: C_n = (1/(n+1))·binom(2n,n)

5. Dry Run Example

C0=1, C1=1, C2=2, C3=5 — five parenthesis strings for n=3.


6. Key Properties

PropertyValue
GrowthRoughly ~4ⁿ
ModOften compute modulo prime

7. Where It Is Used

DomainUse
Competitive programmingGrid paths not crossing diagonal
CS theoryEnumeration of structures

8. Interview Tips

Derive recurrence from BST count or parentheses; know modular inverse for closed form under modulo.


9. Comparison with Other Algorithms

ApproachCost
DP recurrenceO()
Closed formO(n) with binomial

10. Complexity

MetricValue
TimeO() DP
SpaceO(n)

Implementation Example (PYTHON)

def catalan(n: int) -> int:
    if n <= 1:
        return 1
    dp = [0] * (n + 1)
    dp[0] = dp[1] = 1
    for k in range(2, n + 1):
        for i in range(k):
            dp[k] += dp[i] * dp[k - 1 - i]
    return dp[n]

Interactive Visualizer Workspace

Explore step-by-step interactive animations, memory state tracking, and live multi-language execution in DrawCode.

Launch Interactive Visualizer