The Wayback Machine - https://web.archive.org/web/20240811221202/https://www.geeksforgeeks.org/count-permutations-of-given-array-that-generates-the-same-binary-search-tree-bst/
Open In App

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

Last Updated : 18 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 greater 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++




// 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;
}


Java




// 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


Python3




# Python3 program to implement
# the above approach
 
# Function to precompute the
# factorial of 1 to N
def 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 nCr
def 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 BST
def 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 Code
if __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 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


Javascript




<script>
 
// JavaScript program to implement
// the above approach
 
// Function to precompute the
// factorial of 1 to N
function 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 nCr
function 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 BST
function 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 Code
 
var arr = [];
arr = [3, 4, 5, 1, 2];
 
// Store the size of arr
var N = arr.length;
 
// Store the factorial up to N
var fact = Array(N);
 
// Precompute the factorial up to N
calculateFact(fact, N);
document.write( countWays(arr, fact));
 
</script>


Output: 

6

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



Similar Reads

Count divisors which generates same Quotient and Remainder
Given a positive integer N, the task is to find the count of all the numbers M such that when the number N is divided by M, the quotient is equal to its remainder i.e (?N/M? = N mod M) where ? ? denotes the floor value of a given number. Examples: Input: N = 8Output: 2Explanation: When 8 is divided by 3 and 7, it returns the same Quotient and Remai
7 min read
Check if concatenation of any permutation of given list of arrays generates the given array
Given an array arr[] of N distinct integers and a list of arrays pieces[] of distinct integers, the task is to check if the given list of arrays can be concatenated in any order to obtain the given array. If it is possible, then print "Yes". Otherwise, print "No". Examples: Input: arr[] = {1, 2, 4, 3}, pieces[][] = {{1}, {4, 3}, {2}}Output: YesExpl
9 min read
Median of all nodes from a given range in a Binary Search Tree ( BST )
Given a Binary Search Tree (BST)consisting of N nodes and two nodes A and B, the task is to find the median of all the nodes in the given BST whose values lie over the range [A, B]. Examples: Input: A = 3, B = 11 Output: 6Explanation:The nodes that lie over the range [3, 11] are {3, 4, 6, 8, 11}. The median of the given nodes is 6. Input: A = 6, B
10 min read
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Generate all binary permutations such that there are more or equal 1's than 0's before every point in all permutations
Generate all permutations of a given length such that every permutation has more or equals 1's than 0's in all prefixes of the permutation. Examples: Input: len = 4 Output: 1111 1110 1101 1100 1011 1010 Note that a permutation like 0101 can not be in output because there are more 0's from index 0 to 2 in this permutation. Input: len = 3 Output: 111
5 min read
Count of pairs of integers up to X and Y that generates equal Quotient and Remainder
Given two integers X and Y, the task is to count the number of pairs (m, n), such that m / n = m % n and 1 ? m ? x and 1 ? n ? y. Examples: Input: X = 4, Y = 5 Output: 2 Explanation: The pairs (3, 2) and (4, 3) satisfy the condition. Input: X = 3, Y = 1 Output : 0 Approach: The given problem can be solved based on the following observations: For th
4 min read
Binary Search Tree (BST) Traversals – Inorder, Preorder, Post Order
Given a Binary Search Tree, The task is to print the elements in inorder, preorder, and postorder traversal of the Binary Search Tree. Input: Output: Inorder Traversal: 10 20 30 100 150 200 300Preorder Traversal: 100 20 10 30 200 150 300Postorder Traversal: 10 30 20 150 300 200 100 Input: Output: Inorder Traversal: 8 12 20 22 25 30 40Preorder Trave
11 min read
Implement Binary Search Tree(BST) Iterator
Binary Search Trees (BSTs) are data structures, in computer science. They are commonly used for searching, insertion and deletion operations. In situations it becomes necessary to traverse a BST in an order. For example an in order traversal visits nodes in ascending order based on their values. This article explores the creation of a BSTIterator c
6 min read
Insertion in Binary Search Tree (BST)
Given a BST, the task is to insert a new node in this BST. Example: How to Insert a value in a Binary Search Tree:A new key is always inserted at the leaf by maintaining the property of the binary search tree. We start searching for a key from the root until we hit a leaf node. Once a leaf node is found, the new node is added as a child of the leaf
15 min read
Deletion in Binary Search Tree (BST)
Given a BST, the task is to delete a node in this BST, which can be broken down into 3 scenarios: Case 1. Delete a Leaf Node in BST Case 2. Delete a Node with Single Child in BST Deleting a single child node is also simple in BST. Copy the child to the node and delete the node.  Case 3. Delete a Node with Both Children in BST Deleting a node with b
10 min read
three90RightbarBannerImg