Find Nth Catalan Number (Tabulation)

C 0 = C 1 = 1 and C n = (2n)! ((n+1)!n!) = i=0 n-1 C i C n-1-i = 2(2n-1) n+1 C n-1 for n > 2

Hint

Building upon understanding of Catalan number (Memoization). Tabulation essentially reconstructs the cache.

Start with the foundation – the base cases, which are the simplest solutions. Then, layer by layer, use the results of the previous layers to calculate the solutions for the next level. This way, we systematically build up the entire solution, avoiding redundant calculations and ensuring efficiency. It is like building a pyramid.

The underlying calculation logic remains fundamentally identical to the original recursive approach, albeit executed in reverse order.

# Python implementation
def C(n):
  cache = [0 for _ in range(n + 1)]

  cache[0] = cache[1] = 1

  for i in range(2, n + 1):
    result = 0

    for j in range(i):
      result += cache[j] * cache[i - 1 - j]
    
    cache[i] = result

  return cache[n]

n = 5

print(C(n))
// Javascript implementation
function C(n) {
  const cache = new Array(n + 1).fill(0);

  cache[0] = cache[1] = 1;

  for (let i = 2; i < n + 1; i++) {
    let result = 0;

    for (let j = 0; j < i; j++) {
      result += cache[j] * cache[i - 1 - j];
    }

    cache[i] = result;
  }

  return cache[n];
}

const n = 5;

console.log(C(n));