The Wayback Machine - https://web.archive.org/web/20240922064834/https://www.geeksforgeeks.org/python-program-for-program-for-nth-catalan-number/
Open In App

Python Program for nth Catalan Number

Last Updated : 13 Jun, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Catalan numbers are a sequence of natural numbers that occurs in many interesting counting problems like the following.

1) Count the number of expressions containing n pairs of parentheses which are correctly matched. For n = 3, possible expressions are ((())), ()(()), ()()(), (())(), (()()).

2) Count the number of possible Binary Search Trees with n keys (See this) 

See this for more applications. 

The first few Catalan numbers for n = 0, 1, 2, 3, … are 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, …

Recursive Solution 

Catalan numbers satisfy the following recursive formula. 
C_0=1 \ and \ C_n_+_1=\sum_{i=0}^{n}C_iC_n_-_i \ for \ n\geq 0;

Following is the implementation of above recursive formula.  

Python3

# A recursive function to find nth catalan number
def catalan(n):
    # Base Case
    if n <= 1:
        return 1
 
    # Catalan(n) is the sum of catalan(i)*catalan(n-i-1)
    res = 0
    for i in range(n):
        res += catalan(i) * catalan(n-i-1)
 
    return res
 
 
# Driver Program to test above function
for i in range(10):
    print(catalan(i), end=' ')

                    

Output: 
1 1 2 5 14 42 132 429 1430 4862

 

Time Complexity: O(2n)

Auxiliary Space:  O(n)

Dynamic Programming Solution 

We can observe that the above recursive implementation does a lot of repeated work (we can the same by drawing a recursion tree). Since there are overlapping sub-problems, we can use dynamic programming for this. Following is a Dynamic programming-based implementation in Python.  

Python3

# A dynamic programming based function to find nth
# Catalan number
 
def catalan(n):
    if (n == 0 or n == 1):
        return 1
 
    # Table to store results of subproblems
    catalan = [0 for i in range(n + 1)]
 
    # Initialize first two values in table
    catalan[0] = 1
    catalan[1] = 1
 
    # Fill entries in catalan[] using recursive formula
    for i in range(2, n + 1):
        catalan[i] = 0
        for j in range(i):
            catalan[i] += catalan[j] * catalan[i-j-1]
 
    # Return last entry
    return catalan[n]
 
 
# Driver code
for i in range(10):
    print(catalan(i))

                    

Output: 
1
1
2
5
14
42
132
429
1430
4862

 

Time Complexity: O(n^2)
Auxiliary Space: O(n)
 

Please refer complete article on Program for nth Catalan Number for more details!



Similar Reads

Python Program for nth multiple of a number in Fibonacci Series
Given two integers n and k. Find position the nth multiple of K in the Fibonacci series. Examples: Input: k = 2, n = 3Output: 9, 3rd multiple of 2 in Fibonacci Series is 34 that appears at position 9. Input: k = 4, n = 5 Output: 30, 5th multiple of 4 in Fibonacci Series is 832040 which appears at position 30. An Efficient Solution is based on the b
5 min read
Python program to remove Nth occurrence of the given word
Given a list of words in Python, the task is to remove the Nth occurrence of the given word in that list. Examples: Input: list - ["geeks", "for", "geeks"] word = geeks, N = 2 Output: list - ["geeks", "for"]Input: list - ["can", "you", "can", "a", "can" "?"] word = can, N = 1 Output: list - ["you", "can", "a", "can" "?"] Approach #1: By taking anot
8 min read
Python Program to Remove Nth element from Kth key's value from the dictionary
Given a dictionary with value lists, our task is to write a Python program to remove N element from Kth key's values. Examples: Input : test_dict = {"gfg" : [9, 4, 5, 2, 3, 2], "is" : [1, 2, 3, 4, 3, 2], "best" : [2, 2, 2, 3, 4]}, K, N = "gfg", 2Output : {'gfg': [9, 4, 5, 3], 'is': [1, 2, 3, 4, 3, 2], 'best': [2, 2, 2, 3, 4]}Explanation : 2 removed
9 min read
Python program to remove the nth index character from a non-empty string
Given a String, the task is to write a Python program to remove the nth index character from a non-empty string Examples: Input: str = "Stable" Output: Modified string after removing 4 th character Stabe Input: str = "Arrow" Output: Modified string after removing 4 th character Arro The first approach uses a new string variable for storing the modi
4 min read
Python program to replace every Nth character in String
Given a string, the task is to write a Python program to replace every Nth character in a string by the given value K. Examples: Input : test_str = "geeksforgeeks is best for all geeks", K = '$', N = 5 Output : geeks$orge$ks i$ bes$ for$all $eeks Explanation : Every 5th character is converted to $. Input : test_str = "geeksforgeeks is best for all
5 min read
Python program to get the nth weekday after a given date
Given a date and weekday index, the task is to write a Python program to get the date for the given day of the week occurring after the given date. The weekday index is based on the below table: IndexWeekday0Monday1Tuesday2Wednesday3Thursday4Friday5Saturday6Sunday Examples: Input : test_date = datetime.datetime(2017, 3, 14), weekday_idx = 4Output :
3 min read
Python Program For Writing A Function To Get Nth Node In A Linked List
Write a GetNth() function that takes a linked list and an integer index and returns the data value stored in the node at that index position. Example: Input: 1-&gt;10-&gt;30-&gt;14, index = 2 Output: 30 The node at index 2 is 30Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Algorithm: 1. Initialize count = 0 2.
4 min read
Python - Insert after every Nth element in a list
Sometimes we need to perform a single insertion in python, this can be easily done with the help of the insert function. But sometimes, we require to insert in a repeated manner after every n numbers, for that there can be numerous shorthands that can be quite handy. Lets discuss certain ways in which this can be done. Method #1 : Using join() + en
7 min read
Python | Ways to find nth occurrence of substring in a string
Given a string and a substring, write a Python program to find the nth occurrence of the string. Let's discuss a few methods to solve the given task. Get Nth occurrence of a substring in a String using regex Here, we find the index of the 'ab' character in the 4th position using the regex re.finditer() C/C++ Code import re # Initialising values ini
4 min read
Python | Check for Nth index existence in list
Sometimes, while working with lists, we can have a problem in which we require to insert a particular element at an index. But, before that it is essential to know that particular index is part of list or not. Let's discuss certain shorthands that can perform this task error free. Method #1 : Using len() This task can be performed easily by finding
3 min read
Python | Sort tuple list by Nth element of tuple
Sometimes, while working with Python list, we can come across a problem in which we need to sort the list according to any tuple element. These must be a generic way to perform the sort by particular tuple index. This has a good utility in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using sort(
8 min read
Python | Selective Merge list every Nth position
Sometimes, while working with Python list, we can come into a problem in which we need to perform merging in list. A simple merge of list is easier to perform. But sometimes, we need to handle variations in merge. One such can be merge one list with other at every Nth element. This particular problem can be faced in day-day programming and competit
5 min read
Python | Nth Column vertical string in Matrix
Sometimes, while working with Python Matrix, we can have a problem in which we need to access the Matrix in vertical form and extract strings from the same, that too as a string, not merely as a list of characters. This task has its application in gaming in which we need to extract strings during crosswords. Let's discuss a way in which this task c
7 min read
Python | Search in Nth Column of Matrix
Sometimes, while working with Python Matrix, we can have a problem in which we need to check if an element is present or not. This problem is simpler, but a variation to it can be to perform a check in a particular column of Matrix. Let's discuss a shorthand by which this task can be performed. Method 1: Using any() + list comprehension This task c
10 min read
Python | Search in Nth column in list of tuples
Sometimes, while working with Python list, we can have a data set that consists of tuples and we have a problem in which we need to search the element in the Nth column of list. This has it's applications in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using enumerate() + list comprehension In t
7 min read
Python | Replace tuple according to Nth tuple element
Sometimes, while working with data, we might have a problem in which we need to replace the entry in which a particular entry of data is matching. This can be a matching phone no, id etc. This has it's application in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + enumerate() This task
8 min read
Python | Counting Nth tuple element
Sometimes, while working with Python, we can have a problem in which we need to count the occurrence of a particular's elements. This kind of problem is quite common while working with records. Let's discuss a way in which this task can be performed. Method #1 : Using Counter() + generator expression The combination of above functionalities can be
5 min read
Python - Get Nth word in given String
Sometimes, while working with data, we can have a problem in which we need to get the Nth word of a String. This kind of problem has many application in school and day-day programming. Let's discuss certain ways in which this problem can be solved. Method #1 : Using loop This is one way in which this problem can be solved. In this, we run a loop an
4 min read
Python | Minimum K records of Nth index in tuple list
Sometimes, while working with data, we can have a problem in which we need to get the minimum of elements filtered by the Nth element of record. This has a very important utility in web development domain. Let’s discuss certain ways in which this task can be performed. Method #1 : Using filter() + lambda + set() + list comprehension The combination
9 min read
Python | Nth tuple index Subtraction by K
Many times, while working with records, we can have a problem in which we need to change the value of tuple elements. This is a common problem while working with tuples. Let’s discuss certain ways in which K can be subtracted to Nth element of tuple in list. Method #1 : Using loop Using loops this task can be performed. In this, we just iterate the
6 min read
Python - Get maximum of Nth column from tuple list
Sometimes, while working with Python lists, we can have a task in which we need to work with tuple list and get the maximum of its Nth index. This problem has application in web development domain while working with data information. Let’s discuss certain ways in which this task can be performed. Method #1: Using list comprehension + max() This tas
7 min read
Python - Get Nth column elements in Tuple Strings
Yet another peculiar problem that might not be common, but can occur in python programming while playing with tuples. Since tuples are immutable, they are difficult to manipulate and hence knowledge of possible variation solutions always helps. This article solves the problem of extracting only the Nth index element of each string in tuple. Let’s d
8 min read
Python - Constant Multiplication to Nth Column
Many times, while working with records, we can have a problem in which we need to change the value of tuple elements. This is a common problem while working with tuples. Let’s discuss certain ways in which K can be multiplied to Nth element of tuple in list. Method #1 : Using loop Using loops this task can be performed. In this, we just iterate the
7 min read
Python | Nth column Matrix Product
Sometimes, while working with Python Matrix, we may have a problem in which we require to find the product of a particular column. This can have a possible application in day-day programming and competitive programming. Let’s discuss certain ways in which this task can be performed. Method #1: Using loop + zip() This task can be solved using a comb
7 min read
Python - Uppercase Nth character
The problem of capitalizing a string is quite common and has been discussed many times. But sometimes, we might have a problem like this in which we need to convert the Nth character of the string to uppercase. Let’s discuss certain ways in which this can be performed. Method #1 : Using string slicing + upper() This task can easily be performed usi
5 min read
Python - Nth smallest Greater than K
This article offers various approaches to solve the problem of finding Nth smallest number in python list greater than a specific element K in python list. This basically provides all the approaches from naive to one-liners so that they can be used in programming whenever required. Method 1 : Naive Method + sort() Using loop we keep on adding eleme
8 min read
Python - Multiply K to every Nth element
We generally wish to employ a particular function to all the elements in a list. But sometimes, according to requirement we would wish to employ a particular functionality to certain elements of the list, basically to every Nth element in list. Let’s discuss certain ways in which this can be performed. Method #1 : Using list comprehension + enumera
5 min read
Python - Remove Record if Nth Column is K
Sometimes while working with a list of records, we can have a problem in which we need to perform the removal of records on the basis of the presence of certain elements at the Nth position of the record. Let us discuss certain ways in which this task can be performed. Method #1: Using loop This is a brute force method in which this task can be per
10 min read
Python - Extract Kth element of every Nth tuple in List
Given list of tuples, extract Kth column element of every Nth tuple. Input :test_list = [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8), (6, 4, 7), (2, 5, 7), (1, 9, 10), (3, 5, 7)], K = 2, N = 3 Output : [3, 8, 10] Explanation : From 0th, 3rd, and 6th tuple, 2nd elements are 3, 8, 10. Input :test_list = [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8), (6,
8 min read
Python - Extract String after Nth occurrence of K character
Given a String, extract the string after Nth occurrence of a character. Input : test_str = 'geekforgeeks', K = "e", N = 2 Output : kforgeeks Explanation : After 2nd occur. of "e" string is extracted. Input : test_str = 'geekforgeeks', K = "e", N = 4 Output : ks Explanation : After 4th occur. of "e" string is extracted. Method #1 : Using split() Thi
7 min read
Article Tags :