Participate in Codex, Test Your Skills & Win BIG

Count Permutations of BST

You are given two positive integers A and B. For all permutations of [1, 2, …, A], we create a BST. Count how many of these have height B.


  1. Values of a permutation are sequentially inserted into the BST by general rules i.e in increasing order of indices.
  2. Height of BST is maximum number of edges between root and a leaf.
  3. Return answer modulo 109 + 7.
  4. Expected time complexity is worst case O(N4).
  5. 1 ≤ N ≤ 50

For example,

A = 3, B = 1

Two permutations [2, 1, 3] and [2, 3, 1] generate a BST of height 1.
In both cases the BST formed is

   / \
  1   3  

Another example,
A = 3, B = 2
Return 4.

Next question, can you do the problem in O(N3)?

NOTE: You only need to implement the given function. Do not read input, instead use the arguments to the function. Do not print the output, instead return values as specified. Still have a doubt? Checkout Sample Codes for more details.
Start solving Count Permutations of BST on Interview Code Editor
  • Hint 1
  • Solution Approach
  • Complete Solution


Click here to start solving coding interview questions