Skip to problem
←

Unique Binary Search Trees

Medium 0 attempts

For a given integer n, count how many distinct binary search tree shapes can be built using exactly the keys 1 through n (a BST being a tree where every node's left subtree holds smaller values and its right subtree holds larger ones).

Use every key exactly once and return only the count, not the trees. Left and right child positions are distinct, so reflected shapes may count separately. Different insertion sequences that produce the same tree count only once.

Function contract

Implement numTrees(n).

Output: Return the exact number of structurally distinct BSTs using each key from 1 through n exactly once. No modulo is required.

Example 1

Input
n = 3
Output
5

Explanation: Choosing root 1 gives two shapes, root 2 gives one, and root 3 gives two: 2 + 1 + 2 = 5.

Example 2

Input
n = 1
Output
1
Constraints
  • 1 <= n <= 19

Count by Root Choice

Let dp[i] count BST shapes on i ordered keys. Choosing a root leaves j smaller keys on the left and i - 1 - j larger keys on the right. Every left shape can pair with every right shape, contributing dp[j] × dp[i - 1 - j]. Sum over all possible j.

Set dp[0] = 1: an empty child is one valid choice, not zero choices. This is an internal base case even though the problem input starts at n = 1. The largest supported answer, for n = 19, is 1,767,263,190 and is exactly representable by JavaScript Number.

javascript
function numTrees(n) {
  const dp = Array(n+1).fill(0);
  dp[0] = dp[1] = 1;
  for (let i = 2; i <= n; i++)
    for (let j = 0; j < i; j++)
      dp[i] += dp[j] * dp[i-1-j];
  return dp[n];
}

Time: O(n²) | Space: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript