![]() |
VOOZH | about |
Given a number n, the task is to find the nth Catalan number. Catalan Number for n is equal to the number of expressions containing n pairs of parenthesis that are correctly matched, i.e., for each of the n(' there exist n ')' on there right and vice versa. The first few Catalan numbers for n = 0, 1, 2, 3, 4, 5… are: 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, ... so on.
Examples:
Input: n = 3
Output: 5
Explanation: For n = 3, there are 5 valid combinations of balanced parentheses: ((())), (()()), (())(), ()(()), ()()()Input: n = 4
Output: 14
Explanation: For n = 4, there are 14 distinct valid combinations of balanced parentheses that can be formed.
Catalan numbers are defined as a mathematical sequence that consists of positive integers, which can be used to find the number of possibilities of various combinations. The nth term in the sequence denoted Cn, is found in the following formula:
Catalan numbers occur in many interesting counting problems like the following.
Refer to this for more applications.
Table of Content
Recursive formula:
The nth Catalan number is calculated using the recursive formula. We recursively compute smaller Catalan values and combine them.
Algorithm:
5
Time Complexity: O(2n)
Auxiliary Space: O(n)
The recursive solution has overlapping subproblems. So, we store previously computed Catalan numbers in an array and build the result from bottom-up using the same formula:
Algorithm:
catalan[] of size n+1 and Initialize catalan[0] = catalan[1] = 1. i from 2 to n. For each i, initialize catalan[i] = 0. j from 0 to i-1. Add catalan[j] * catalan[i - j - 1] to catalan[i]. catalan[n].5
Time Complexity: O(n2)
Auxiliary Space: O(n)
Catalan numbers can be directly computed using the mathematical formula:
Instead of recursion or DP, we efficiently compute the binomial coefficient and divide by (n + 1).
5
Time Complexity: O(n).
Auxiliary Space: O(1)
We already know how to calculate the nth Catalan Number using the below formula,
This formula can be further simplified to express the nth Catalan Number in the terms of (n-1)th Catalan Number,
Steps:
5
Time Complexity: O(n)
Auxiliary Space: O(1)