Unique Binary Search Trees - Problem

Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n.

A Binary Search Tree (BST) is a tree where for each node:

  • All values in the left subtree are less than the node's value
  • All values in the right subtree are greater than the node's value

Structurally unique means trees with different shapes, even if they contain the same values in different arrangements.

Input & Output

Example 1 — Small Case
$ Input: n = 3
Output: 5
💡 Note: With 3 nodes (1,2,3), we can form 5 structurally unique BSTs: root=1 gives 2 trees, root=2 gives 1 tree, root=3 gives 2 trees. Total: 2+1+2=5
Example 2 — Base Case
$ Input: n = 1
Output: 1
💡 Note: With only 1 node, there's exactly 1 way to form a BST - just a single node tree
Example 3 — Two Nodes
$ Input: n = 2
Output: 2
💡 Note: With 2 nodes (1,2), we can form 2 BSTs: root=1 with right child 2, or root=2 with left child 1

Constraints

  • 1 ≤ n ≤ 19

Visualization

Tap to expand
Unique Binary Search Trees INPUT n = 3 Available nodes: 1 2 3 BST Property: Left subtree < Node Right subtree > Node Count structurally unique trees Example BST structure: R L R ALGORITHM STEPS 1 Define DP Array dp[i] = unique BSTs with i nodes 2 Base Cases dp[0]=1, dp[1]=1 (empty/single) 3 Recurrence Relation dp[n] = Sum of dp[i-1]*dp[n-i] 4 Calculate dp[3] Try each node as root DP Table (Catalan Numbers) i 0 1 2 3 dp[i] 1 1 2 5 dp[3]=dp[0]*dp[2]+dp[1]*dp[1]+dp[2]*dp[0] =1*2 + 1*1 + 2*1 = 5 Root choices: 1, 2, or 3 2 + 1 + 2 = 5 structures FINAL RESULT Output: 5 5 unique BST structures All 5 Unique BSTs: 1 2 3 1 3 2 2 1 3 3 2 1 3 1 2 OK - Verified! Catalan(3) = 5 Key Insight: The number of unique BSTs with n nodes follows the Catalan number sequence: C(n) = (2n)! / ((n+1)! * n!) For each root i, we have dp[i-1] left subtree choices and dp[n-i] right subtree choices. Time Complexity: O(n^2) | Space Complexity: O(n) using dynamic programming. TutorialsPoint - Unique Binary Search Trees | Dynamic Programming (Catalan Numbers)
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
230.6K Views
Medium Frequency
~15 min Avg. Time
8.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen