
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find number of possible BSTs can be generated using n distinct nodes in Python
Suppose we have a number n. If we have numbers like [1,2,...,n] we have to count number ofpossible BSTs can be formed using these n values. If the answer is too large, then mod the result by 10^9+7.
So, if the input is like n = 3, then the output will be 14,
To solve this, we will follow these steps
- a := a list with values [0, 1]
- m := 10^9+7
- max_n := 1000
- for k in range 2 to max_n + 1, do
- insert (1 + sum of all elements of the list (a[i] * a[k - i] for all i in range(1, k))) mod m at the end of a
- return (a[n + 1] - 1) mod m
Example
Let us see the following implementation to get better understanding −
def solve(n): a = [0, 1] m = 10**9+7 max_n = 1000 for k in range(2, max_n + 2): a.append((1 + sum(a[i] * a[k - i] for i in range(1, k))) % m) return ((a[n + 1] - 1) % m) n = 3 print(solve(n))
Input
3
Output
14
- Related Articles
- Program to find number of good leaf nodes pairs using Python
- Program to count number of BST with n nodes in Python
- Program to find number of distinct subsequences in Python
- Program to find minimum number of vertices to reach all nodes using Python
- Program to find maximum number of K-sized groups with distinct type items are possible in Python
- Program to find number of nodes in a range in Python
- Program to find number of ways we can get n R.s using Indian denominations in Python
- C++ Program to find minimum possible unlancedness of generated string T
- Python program to create a doubly linked list of n nodes and count the number of nodes
- Python program to create a Circular Linked List of N nodes and count the number of nodes
- Program to find possible number of palindromes we can make by trimming string in Python
- Program to find number of nodes in the sub-tree with the same label using Python
- How can autoencoder be generated using an encoder and decoder using Python?
- Program to find number of distinct coin sums we can make with coins and quantities in Python?
- C++ Program to find out the number of unique matrices that can be generated by swapping rows and columns

Advertisements