VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-permutations-of-given-array-that-generates-the-same-binary-search-tree-bst/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 15 Jul, 2025

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.

Output: 
6

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

Comment