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++
#include <bits/stdc++.h>
using namespace std;
void calculateFact( int fact[], int N)
{
fact[0] = 1;
for ( long long int i = 1; i < N; i++) {
fact[i] = fact[i - 1] * i;
}
}
int nCr( int fact[], int N, int R)
{
if (R > N)
return 0;
int res = fact[N] / fact[R];
res /= fact[N - R];
return res;
}
int countWays(vector< int >& arr, int fact[])
{
int N = arr.size();
if (N <= 2) {
return 1;
}
vector< int > leftSubTree;
vector< int > rightSubTree;
int root = arr[0];
for ( int i = 1; i < N; i++) {
if (arr[i] < root) {
leftSubTree.push_back(
arr[i]);
}
else {
rightSubTree.push_back(
arr[i]);
}
}
int N1 = leftSubTree.size();
int N2 = rightSubTree.size();
int countLeft
= countWays(leftSubTree,
fact);
int countRight
= countWays(rightSubTree,
fact);
return nCr(fact, N - 1, N1)
* countLeft * countRight;
}
int main()
{
vector< int > arr;
arr = { 3, 4, 5, 1, 2 };
int N = arr.size();
int fact[N];
calculateFact(fact, N);
cout << countWays(arr, fact);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void calculateFact( int fact[], int N)
{
fact[ 0 ] = 1 ;
for ( int i = 1 ; i < N; i++)
{
fact[i] = fact[i - 1 ] * i;
}
}
static int nCr( int fact[], int N, int R)
{
if (R > N)
return 0 ;
int res = fact[N] / fact[R];
res /= fact[N - R];
return res;
}
static int countWays(Vector<Integer> arr,
int fact[])
{
int N = arr.size();
if (N <= 2 )
{
return 1 ;
}
Vector<Integer> leftSubTree = new Vector<Integer>();
Vector<Integer> rightSubTree = new Vector<Integer>();
int root = arr.get( 0 );
for ( int i = 1 ; i < N; i++)
{
if (arr.get(i) < root)
{
leftSubTree.add(arr.get(i));
}
else
{
rightSubTree.add(arr.get(i));
}
}
int N1 = leftSubTree.size();
int N2 = rightSubTree.size();
int countLeft = countWays(leftSubTree,
fact);
int countRight = countWays(rightSubTree,
fact);
return nCr(fact, N - 1 , N1) *
countLeft * countRight;
}
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);
int N = a.length;
int []fact = new int [N];
calculateFact(fact, N);
System.out.print(countWays(arr, fact));
}
}
|
Python3
def calculateFact(fact: list , N: int ) - > None :
fact[ 0 ] = 1
for i in range ( 1 , N):
fact[i] = fact[i - 1 ] * i
def nCr(fact: list , N: int , R: int ) - > int :
if (R > N):
return 0
res = fact[N] / / fact[R]
res / / = fact[N - R]
return res
def countWays(arr: list , fact: list ) - > int :
N = len (arr)
if (N < = 2 ):
return 1
leftSubTree = []
rightSubTree = []
root = arr[ 0 ]
for i in range ( 1 , N):
if (arr[i] < root):
leftSubTree.append(arr[i])
else :
rightSubTree.append(arr[i])
N1 = len (leftSubTree)
N2 = len (rightSubTree)
countLeft = countWays(leftSubTree, fact)
countRight = countWays(rightSubTree, fact)
return (nCr(fact, N - 1 , N1) *
countLeft * countRight)
if __name__ = = '__main__' :
arr = [ 3 , 4 , 5 , 1 , 2 ]
N = len (arr)
fact = [ 0 ] * N
calculateFact(fact, N)
print (countWays(arr, fact))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void calculateFact( int []fact, int N)
{
fact[0] = 1;
for ( int i = 1; i < N; i++)
{
fact[i] = fact[i - 1] * i;
}
}
static int nCr( int []fact, int N, int R)
{
if (R > N)
return 0;
int res = fact[N] / fact[R];
res /= fact[N - R];
return res;
}
static int countWays(List< int > arr,
int []fact)
{
int N = arr.Count;
if (N <= 2)
{
return 1;
}
List< int > leftSubTree = new List< int >();
List< int > rightSubTree = new List< int >();
int root = arr[0];
for ( int i = 1; i < N; i++)
{
if (arr[i] < root)
{
leftSubTree.Add(arr[i]);
}
else
{
rightSubTree.Add(arr[i]);
}
}
int N1 = leftSubTree.Count;
int N2 = rightSubTree.Count;
int countLeft = countWays(leftSubTree,
fact);
int countRight = countWays(rightSubTree,
fact);
return nCr(fact, N - 1, N1) *
countLeft * countRight;
}
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);
int N = a.Length;
int []fact = new int [N];
calculateFact(fact, N);
Console.Write(countWays(arr, fact));
}
}
|
Javascript
<script>
function calculateFact(fact, N)
{
fact[0] = 1;
for ( var i = 1; i < N; i++) {
fact[i] = fact[i - 1] * i;
}
}
function nCr(fact, N, R)
{
if (R > N)
return 0;
var res = parseInt(fact[N] / fact[R]);
res = parseInt(res / fact[N - R]);
return res;
}
function countWays(arr, fact)
{
var N = arr.length;
if (N <= 2) {
return 1;
}
var leftSubTree = [];
var rightSubTree = [];
var root = arr[0];
for ( var i = 1; i < N; i++) {
if (arr[i] < root) {
leftSubTree.push(
arr[i]);
}
else {
rightSubTree.push(
arr[i]);
}
}
var N1 = leftSubTree.length;
var N2 = rightSubTree.length;
var countLeft
= countWays(leftSubTree,
fact);
var countRight
= countWays(rightSubTree,
fact);
return nCr(fact, N - 1, N1)
* countLeft * countRight;
}
var arr = [];
arr = [3, 4, 5, 1, 2];
var N = arr.length;
var fact = Array(N);
calculateFact(fact, N);
document.write( countWays(arr, fact));
</script>
|
Time Complexity: O(N2)
Auxiliary Space: O(N)
Last Updated :
18 Aug, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...