find the nth catalan number in typescript

To find the nth Catalan number in TypeScript, we can use either recursion or dynamic programming.

Using Recursion

index.ts
function catalanNumberRecursive(n: number): number {
  if (n <= 1) {
    return 1;
  }

  let result = 0;
  for (let i = 0; i < n; i++) {
    result += catalanNumberRecursive(i) * catalanNumberRecursive(n - i - 1);
  }

  return result;
}
239 chars
13 lines

Using Dynamic Programming

index.ts
function catalanNumberDP(n: number): number {
  const dp: number[] = new Array(n + 1).fill(0);
  
  // Base case
  dp[0] = 1;
  dp[1] = 1;

  for (let i = 2; i <= n; i++) {
    for (let j = 0; j < i; j++) {
      dp[i] += dp[j] * dp[i - j - 1];
    }
  }

  return dp[n];
}
274 chars
16 lines

Both the above solutions have a time complexity of O(n^2) and a space complexity of O(n).

gistlibby LogSnag