Count permutations of given array that generates the same Binary Search Tree (BST)

Given an array, arr[] of size N consisting of elements from the range [1, N], that represents the order, in which the elements are inserted into a Binary Search Tree, the task is to count the number of ways to rearrange the given array to get the same BST.

Examples:

Input: arr[ ] ={3, 4, 5, 1, 2}
Output: 6
Explanation :
The permutations of the array which represent the same BST are:{{3, 4, 5, 1, 2}, {3, 1, 2, 4, 5}, {3, 1, 4, 2, 5}, {3, 1, 4, 5, 2}, {3, 4, 1, 2, 5}, {3, 4, 1, 5, 2}}. Therefore, the output is 6.

Input: arr[ ] ={2, 1, 6, 5, 4, 3}
Output: 5

Approach: The idea is to first fix the root node and then recursively count the number of ways to rearrange the elements of the left subtree and the elements of the right subtree in such a way that the relative order within the elements of the left subtree and right subtree must be same. Here is the recurrence relation:



countWays(arr) = countWays(left) * countWays(right) * combinations(N, X).
left: Contains all the elements in the left subtree(Elements which are lesser than the root) 
right: Contains all the elements in the right subtree(Elements which are greater than the root) 
N = Total number of elements in arr[] 
X = Total number of elements in left subtree.

Follow the steps below to solve the problem:

  1. Fix the root node of BST, and store the elements of the left subtree(Elements which are lesser than arr[0]), say ctLeft[], and store the elements of the right subtree(Elements which are lesser than arr[0]), say ctRight[].
  2. To generate identical BST, maintain the relative order within the elements of left subtree and the right subtree.
  3. Calculate the number of ways to rearrange the array to generate BST using the above-mentioned recurrence relation.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to implement
// the above approach
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to precompute the
// factorial of 1 to N
void calculateFact(int fact[], int N)
{
    fact[0] = 1;
    for (long long int i = 1; i < N; i++) {
        fact[i] = fact[i - 1] * i;
    }
}
  
// Function to get the value of nCr
int nCr(int fact[], int N, int R)
{
    if (R > N)
        return 0;
  
    // nCr= fact(n)/(fact(r)*fact(n-r))
    int res = fact[N] / fact[R];
    res /= fact[N - R];
  
    return res;
}
  
// Function to count the number of ways
// to rearrange the array to obtain same BST
int countWays(vector<int>& arr, int fact[])
{
    // Store the size of the array
    int N = arr.size();
  
    // Base case
    if (N <= 2) {
        return 1;
    }
  
    // Store the elements of the
    // left subtree of BST
    vector<int> leftSubTree;
  
    // Store the elements of the
    // right subtree of BST
    vector<int> rightSubTree;
  
    // Store the root node
    int root = arr[0];
  
    for (int i = 1; i < N; i++) {
  
        // Push all the elements
        // of the left subtree
        if (arr[i] < root) {
            leftSubTree.push_back(
                arr[i]);
        }
  
        // Push all the elements
        // of the right subtree
        else {
            rightSubTree.push_back(
                arr[i]);
        }
    }
  
    // Store the size of leftSubTree
    int N1 = leftSubTree.size();
  
    // Store the size of rightSubTree
    int N2 = rightSubTree.size();
  
    // Recurrence relation
    int countLeft
        = countWays(leftSubTree,
                    fact);
    int countRight
        = countWays(rightSubTree,
                    fact);
  
    return nCr(fact, N - 1, N1)
           * countLeft * countRight;
}
  
// Driver Code
int main()
{
  
    vector<int> arr;
    arr = { 3, 4, 5, 1, 2 };
  
    // Store the size of arr
    int N = arr.size();
  
    // Store the factorial up to N
    int fact[N];
  
    // Precompute the factorial up to N
    calculateFact(fact, N);
  
    cout << countWays(arr, fact);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement
// the above approach
import java.util.*;
  
class GFG{
  
// Function to precompute the
// factorial of 1 to N
static void calculateFact(int fact[], int N)
{
    fact[0] = 1;
    for(int i = 1; i < N; i++)
    {
        fact[i] = fact[i - 1] * i;
    }
}
  
// Function to get the value of nCr
static int nCr(int fact[], int N, int R)
{
    if (R > N)
        return 0;
  
    // nCr= fact(n)/(fact(r)*fact(n-r))
    int res = fact[N] / fact[R];
    res /= fact[N - R];
  
    return res;
}
  
// Function to count the number of ways
// to rearrange the array to obtain same BST
static int countWays(Vector<Integer> arr,
                     int fact[])
{
      
    // Store the size of the array
    int N = arr.size();
  
    // Base case
    if (N <= 2
    {
        return 1;
    }
  
    // Store the elements of the
    // left subtree of BST
    Vector<Integer> leftSubTree = new Vector<Integer>();
  
    // Store the elements of the
    // right subtree of BST
    Vector<Integer> rightSubTree = new Vector<Integer>();
  
    // Store the root node
    int root = arr.get(0);
  
    for(int i = 1; i < N; i++)
    {
          
        // Push all the elements
        // of the left subtree
        if (arr.get(i) < root)
        {
            leftSubTree.add(arr.get(i));
        }
  
        // Push all the elements
        // of the right subtree
        else 
        {
            rightSubTree.add(arr.get(i));
        }
    }
  
    // Store the size of leftSubTree
    int N1 = leftSubTree.size();
  
    // Store the size of rightSubTree
    int N2 = rightSubTree.size();
  
    // Recurrence relation
    int countLeft = countWays(leftSubTree,
                              fact);
    int countRight = countWays(rightSubTree,
                               fact);
  
    return nCr(fact, N - 1, N1) * 
             countLeft * countRight;
}
  
// Driver Code
public static void main(String[] args)
{
    int []a = { 3, 4, 5, 1, 2 };
      
    Vector<Integer> arr = new Vector<Integer>();
    for(int i : a)
        arr.add(i);
          
    // Store the size of arr
    int N = a.length;
  
    // Store the factorial up to N
    int []fact = new int[N];
  
    // Precompute the factorial up to N
    calculateFact(fact, N);
  
    System.out.print(countWays(arr, fact));
}
}
  
// This code is contributed by Amit Katiyar

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
  
class GFG{
  
// Function to precompute the
// factorial of 1 to N
static void calculateFact(int []fact, int N)
{
    fact[0] = 1;
    for(int i = 1; i < N; i++)
    {
        fact[i] = fact[i - 1] * i;
    }
}
  
// Function to get the value of nCr
static int nCr(int []fact, int N, int R)
{
    if (R > N)
        return 0;
  
    // nCr= fact(n)/(fact(r)*fact(n-r))
    int res = fact[N] / fact[R];
    res /= fact[N - R];
  
    return res;
}
  
// Function to count the number of ways
// to rearrange the array to obtain same BST
static int countWays(List<int> arr,
                     int []fact)
{
      
    // Store the size of the array
    int N = arr.Count;
  
    // Base case
    if (N <= 2) 
    {
        return 1;
    }
  
    // Store the elements of the
    // left subtree of BST
    List<int> leftSubTree = new List<int>();
  
    // Store the elements of the
    // right subtree of BST
    List<int> rightSubTree = new List<int>();
  
    // Store the root node
    int root = arr[0];
  
    for(int i = 1; i < N; i++)
    {
          
        // Push all the elements
        // of the left subtree
        if (arr[i] < root)
        {
            leftSubTree.Add(arr[i]);
        }
  
        // Push all the elements
        // of the right subtree
        else
        {
            rightSubTree.Add(arr[i]);
        }
    }
  
    // Store the size of leftSubTree
    int N1 = leftSubTree.Count;
  
    // Store the size of rightSubTree
    int N2 = rightSubTree.Count;
  
    // Recurrence relation
    int countLeft = countWays(leftSubTree,
                              fact);
    int countRight = countWays(rightSubTree,
                               fact);
  
    return nCr(fact, N - 1, N1) * 
             countLeft * countRight;
}
  
// Driver Code
public static void Main(String[] args)
{
    int []a = { 3, 4, 5, 1, 2 };
      
    List<int> arr = new List<int>();
    foreach(int i in a)
        arr.Add(i);
          
    // Store the size of arr
    int N = a.Length;
  
    // Store the factorial up to N
    int []fact = new int[N];
  
    // Precompute the factorial up to N
    calculateFact(fact, N);
  
    Console.Write(countWays(arr, fact));
}
}
  
// This code is contributed by Amit Katiyar

chevron_right


Output: 

6

Time Complexity: O(N2)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : amit143katiyar