Number of BSTs from each array element

Last Updated : 14 Oct, 2025

Given an array arr[] of distinct integers. Find the number of Binary Search Trees that can be made using each element in arr[] as a root node.
Examples:

Input: arr[] = [2, 1, 3]
Output: [1, 2, 2] 
Explanation:

4

Input: arr[] = [2, 1]
Output: [1, 1]

Try It Yourself
redirect icon

Approach: Using Catalan numbers - O(n log(n)) Time and O(n) Space

If we pick node k as the root:

  • All nodes with values less than k must go to the left subtree.
  • All nodes with values greater than k must go to the right subtree.

The left and right subtrees themselves each must form valid BSTs, and their counts depend on how many nodes they contain.

Thus,

No. of BSTs rooted at k

= No. of BSTs with (k1) nodes on the left * No. of BSTs with (k2) nodes on the right

= T(k1) * T(k2)

such that T(i) denotes the number of BSTs with i distinct values.

where:
k1​ = number of elements less than k,
k2​ = number of elements greater than k, and
k1+k2=n−1

For a sorted list of nodes a1,a2,…,an​, each element acts as the root.
Thus, the total number of BSTs is:

T(n)=∑(i=1 to n) T(i−1)×T(n−i)

This is because for element at index i( 1 ≤ i ≤ n), there are i-1 elements on left and n-i elements on right.

and T(0) = 1, T(1) = 1, as there is only one BST with either 0 or 1 element.

This recurrence is the same as that of the Catalan numbers, so the number of BSTs with n distinct nodes is Cn​.

Cn=∑(i=0 to n−1) Ci×C(n−1−i)

and, C0=1, C1 = 1.

Therefore, using this we can say that the number of BSTs with element k as the root node are:

C(i) * C(n-i-1)

where i is the the number of nodes with values less than k.

C++
//Driver Code Starts
#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;
//Driver Code Ends


// Precompute factorials up to 2*n
vector<int> computeFact(int num) {
    vector<int> fact(num + 1);
    fact[0] = 1;
    for (int i = 1; i <= num; i++)
        fact[i] = fact[i - 1] * i;
    return fact;
}

// Compute nth Catalan number using precomputed factorials
int catalan(int n, vector<int>& fact) {
    return fact[2 * n] / (fact[n] * fact[n + 1]);
}

// Function to count number of BSTs for each element as root
vector<int> countBSTs(vector<int>& arr) {

    int n = arr.size();
    vector<vector<int>> sorted;

    // Pair each element with its index and sort by value
    for (int i = 0; i < n; i++)
        sorted.push_back({arr[i], i});
    sort(sorted.begin(), sorted.end());

    // Precompute factorials up to 2*n
    vector<int> fact = computeFact(2 * n);

    vector<int> numBSTs(n);

    // Compute BST count for each element as root
    for (int i = 0; i < n; i++) {
        int j = sorted[i][1];
        numBSTs[j] = catalan(i, fact) * catalan(n - i - 1, fact);
    }

    return numBSTs;
}


//Driver Code Starts
int main() {
    vector<int> arr = {2, 1, 3};

    vector<int> numBSTs = countBSTs(arr);
    for (int val : numBSTs)
        cout << val << " ";
    cout << endl;

    return 0;
}
//Driver Code Ends
Java
//Driver Code Starts
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

class GFG {
//Driver Code Ends

    
    // Precompute factorials up to 2*n
    static ArrayList<Integer> computeFact(int num) {
        ArrayList<Integer> fact = new ArrayList<>(Collections.nCopies(num + 1, 1));
        for (int i = 1; i <= num; i++)
            fact.set(i, fact.get(i - 1) * i);
        return fact;
    }

    // Compute nth Catalan number using precomputed factorials
    static int catalan(int n, ArrayList<Integer> fact) {
        return fact.get(2 * n) / (fact.get(n) * fact.get(n + 1));
    }

    // Function to count number of BSTs for each element as root
    static ArrayList<Integer> countBSTs(int[] arr) {

        int n = arr.length;
        int[][] sorted = new int[n][2];

        // Pair each element with its index and sort by value
        for (int i = 0; i < n; i++) {
            sorted[i][0] = arr[i];
            sorted[i][1] = i;
        }
        Arrays.sort(sorted, Comparator.comparingInt(a -> a[0]));

        ArrayList<Integer> fact = computeFact(2 * n);

        ArrayList<Integer> numBSTs = new ArrayList<>(Collections.nCopies(n, 0));

        // Compute BST count for each element as root
        for (int i = 0; i < n; i++) {
            int j = sorted[i][1];
            numBSTs.set(j, catalan(i, fact) * catalan(n - i - 1, fact));
        }

        return numBSTs;
    }
    

//Driver Code Starts
    public static void main (String[] args) {
        int arr[] = {2, 1, 3};
        
        ArrayList<Integer> numBSTs= countBSTs(arr);
        for( int val : numBSTs) {
            System.out.print(val + " ");
        }
        System.out.println();
    }
}
//Driver Code Ends
Python
#Driver Code Starts
import math
#Driver Code Ends


# Precompute factorials up to 2*n
def computeFact(num):
    fact = [1] * (num + 1)
    for i in range(1, num + 1):
        fact[i] = fact[i - 1] * i
    return fact

# Compute nth Catalan number using precomputed factorials
def catalan(n, fact):
    return fact[2 * n] // (fact[n] * fact[n + 1])

# Function to count number of BSTs for each element as root
def countBSTs(arr):
    n = len(arr)
    sortedArr = sorted([(val, idx) for idx, val in enumerate(arr)])
    
    fact = computeFact(2 * n)
    
    numBsts = [0] * n
    
    # Compute BST count for each element as root
    for i, (val, idx) in enumerate(sortedArr):
        numBsts[idx] = catalan(i, fact) * catalan(n - i - 1, fact)
    
    return numBsts
    

#Driver Code Starts
if __name__ == "__main__":   
    arr = [2, 1, 3]
    numBSTs = countBSTs(arr)
    
    print(*numBSTs)
    
#Driver Code Ends
C#
//Driver Code Starts
using System;
using System.Collections.Generic;
using System.Linq;

class GFG {
//Driver Code Ends

    
    // Precompute factorials up to 2*n
    static List<int> computeFact(int num) {
        List<int> fact = Enumerable.Repeat(1, num + 1).ToList();
        for (int i = 1; i <= num; i++)
            fact[i] = fact[i - 1] * i;
        return fact;
    }

    // Compute nth Catalan number using precomputed factorials
    static int catalan(int n, List<int> fact) {
        return fact[2 * n] / (fact[n] * fact[n + 1]);
    }

    // Function to count number of BSTs for each element as root
    static List<int> countBSTs(int[] arr) {
        int n = arr.Length;
        var sorted = arr.Select((val, idx) => new { val, idx })
                        .OrderBy(x => x.val).ToArray();

        List<int> fact = computeFact(2 * n);

        List<int> numBSTs = Enumerable.Repeat(0, n).ToList();

        // Compute BST count for each element as root
        for (int i = 0; i < n; i++) {
            int j = sorted[i].idx;
            numBSTs[j] = catalan(i, fact) * catalan(n - i - 1, fact);
        }

        return numBSTs;
    }


//Driver Code Starts
    static void Main() {
        int[] arr = {2, 1, 3};

        List<int> numBSTs = countBSTs(arr);
        
        Console.WriteLine(string.Join(" ", numBSTs));
    }
}

//Driver Code Ends
JavaScript
// Precompute factorials up to 2*n
function computeFact(num) {
    const fact = Array(num + 1).fill(1);
    for (let i = 1; i <= num; i++)
        fact[i] = fact[i - 1] * i;
    return fact;
}

// Compute nth Catalan number using precomputed factorials
function catalan(n, fact) {
    return fact[2 * n] / (fact[n] * fact[n + 1]);
}

// Function to count number of BSTs for each element as root
function countBSTs(arr) {
    const n = arr.length;
    const sorted = arr.map((val, idx) => ({ val, idx }))
                      .sort((a, b) => a.val - b.val);

    // Precompute factorials up to 2*n
    const fact = computeFact(2 * n);

    const numBSTs = Array(n).fill(0);

    // Compute BST count for each element as root
    for (let i = 0; i < n; i++) {
        const j = sorted[i].idx;
        numBSTs[j] = catalan(i, fact) * catalan(n - i - 1, fact);
    }

    return numBSTs;
}


// Driver Code
//Driver Code Starts
const arr = [2, 1, 3];
const numBSTs = countBSTs(arr)

console.log(...numBSTs);
//Driver Code Ends

Output
1 2 2 
Comment