Program for nth Catalan Number

Pattern: DP recipe: recursion to tabulation

medium

Catalan numbers count, among other things, binary trees with n nodes: choose how many nodes go in the left subtree (i) and the rest go right (n - 1 - i). So C(n) = sum of C(i) × C(n-1-i), with C(0) = 1.

The problem

Return the nth Catalan number modulo 10⁹ + 7. C(5) = 42.

Think first

  • What do Catalan numbers count?
  • If the root of a tree is fixed, how do the other nodes split?
  • What is C(0)?

Hints

    Brute force, and why it fails

    Recursion without memory: exponential.

    The key insight

    Each C(m) depends only on smaller ones, so a table filled from 0 upwards computes them all in O(n²).

    Dry run

    c1 1 2

    C(0) = 1, C(1) = 1. C(2) = C0 C1 + C1 C0 = 2.

    Step 1 of 3

    The plan

    c[0] = 1
    for m in 1..n: c[m] = sum over i of c[i] × c[m - 1 - i]
    

    Complexity

    Time
    O(n²)
    Space
    O(n)

    Each value sums up to n products.

    Edge cases

    • n = 0: 1.
    • n = 1: 1.
    • Large n: use the modulo.
    I've built my logic, show the code

    Java

    class Solution {
        public int findCatalan(int n) {
            final long MOD = 1_000_000_007L;
            long[] c = new long[n + 1];
            c[0] = 1;
            for (int m = 1; m <= n; m++)            // C(m) = sum of C(i) × C(m - 1 - i): choose the root, split the rest
                for (int i = 0; i < m; i++) c[m] = (c[m] + c[i] * c[m - 1 - i]) % MOD;
            return (int) c[n];
        }
    }

    C++

    class Solution {
    public:
        int findCatalan(int n) {
            const long long MOD = 1000000007LL;
            vector<long long> c(n + 1, 0);
            c[0] = 1;
            for (int m = 1; m <= n; m++)            // C(m) = sum of C(i) × C(m - 1 - i): choose the root, split the rest
                for (int i = 0; i < m; i++) c[m] = (c[m] + c[i] * c[m - 1 - i]) % MOD;
            return static_cast<int>(c[n]);
        }
    };

    Python

    class Solution:
        def findCatalan(self, n: int) -> int:
            MOD = 1_000_000_007
            c = [1] + [0] * n
            for m in range(1, n + 1):               # C(m) = sum of C(i) × C(m - 1 - i): choose the root, split the rest
                c[m] = sum(c[i] * c[m - 1 - i] for i in range(m)) % MOD
            return c[n]

    Common mistakes

    • Starting with C(0) = 0.
    • Overflow in the products.

    Similar problems