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:
- 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 greater than arr[0]), say ctRight[].
- To generate identical BST, maintain the relative order within the elements of left subtree and the right subtree.
- Calculate the number of ways to rearrange the array to generate BST using the above-mentioned recurrence relation.
C++
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std;// Function to precompute the// factorial of 1 to Nvoid 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 nCrint 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 BSTint 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 Codeint 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;} |
Java
// Java program to implement// the above approachimport java.util.*;class GFG{// Function to precompute the// factorial of 1 to Nstatic 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 nCrstatic 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 BSTstatic 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 Codepublic 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 |
Python3
# Python3 program to implement# the above approach# Function to precompute the# factorial of 1 to Ndef calculateFact(fact: list, N: int) -> None: fact[0] = 1 for i in range(1, N): fact[i] = fact[i - 1] * i# Function to get the value of nCrdef nCr(fact: list, N: int, R: int) -> int: if (R > N): return 0 # nCr= fact(n)/(fact(r)*fact(n-r)) 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 BSTdef countWays(arr: list, fact: list) -> int: # Store the size of the array N = len(arr) # Base case if (N <= 2): return 1 # Store the elements of the # left subtree of BST leftSubTree = [] # Store the elements of the # right subtree of BST rightSubTree = [] # Store the root node root = arr[0] for i in range(1, N): # Push all the elements # of the left subtree if (arr[i] < root): leftSubTree.append(arr[i]) # Push all the elements # of the right subtree else: rightSubTree.append(arr[i]) # Store the size of leftSubTree N1 = len(leftSubTree) # Store the size of rightSubTree N2 = len(rightSubTree) # Recurrence relation countLeft = countWays(leftSubTree, fact) countRight = countWays(rightSubTree, fact) return (nCr(fact, N - 1, N1) * countLeft * countRight)# Driver Codeif __name__ == '__main__': arr = [ 3, 4, 5, 1, 2 ] # Store the size of arr N = len(arr) # Store the factorial up to N fact = [0] * N # Precompute the factorial up to N calculateFact(fact, N) print(countWays(arr, fact))# This code is contributed by sanjeev2552 |
C#
// C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG{// Function to precompute the// factorial of 1 to Nstatic 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 nCrstatic 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 BSTstatic 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 Codepublic 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 |
Javascript
<script>// JavaScript program to implement// the above approach// Function to precompute the// factorial of 1 to Nfunction calculateFact(fact, N){ fact[0] = 1; for (var i = 1; i < N; i++) { fact[i] = fact[i - 1] * i; }}// Function to get the value of nCrfunction nCr(fact, N, R){ if (R > N) return 0; // nCr= fact(n)/(fact(r)*fact(n-r)) var res = parseInt(fact[N] / fact[R]); res = parseInt(res / fact[N - R]); return res;}// Function to count the number of ways// to rearrange the array to obtain same BSTfunction countWays(arr, fact){ // Store the size of the array var N = arr.length; // Base case if (N <= 2) { return 1; } // Store the elements of the // left subtree of BST var leftSubTree = []; // Store the elements of the // right subtree of BST var rightSubTree = []; // Store the root node var root = arr[0]; for (var i = 1; i < N; i++) { // Push all the elements // of the left subtree if (arr[i] < root) { leftSubTree.push( arr[i]); } // Push all the elements // of the right subtree else { rightSubTree.push( arr[i]); } } // Store the size of leftSubTree var N1 = leftSubTree.length; // Store the size of rightSubTree var N2 = rightSubTree.length; // Recurrence relation var countLeft = countWays(leftSubTree, fact); var countRight = countWays(rightSubTree, fact); return nCr(fact, N - 1, N1) * countLeft * countRight;}// Driver Codevar arr = [];arr = [3, 4, 5, 1, 2];// Store the size of arrvar N = arr.length;// Store the factorial up to Nvar fact = Array(N);// Precompute the factorial up to NcalculateFact(fact, N);document.write( countWays(arr, fact));</script> |
6
Time Complexity: O(N2)
Auxiliary Space: O(N)


