Algorithms · Visualized
DP: Unique BSTs
Dynamic Programming
Break problems into overlapping subproblems and store answers.
Counts how many structurally unique Binary Search Trees can be formed using values 1 to n. Time: O(n²) average, O(n²) worst; space: O(n) — the dp array.
Big-O: The most-asked interview category — 35 classics here.
Unique BSTs (Catalan Number)
Dynamic ProgrammingCounts how many structurally unique Binary Search Trees can be formed using values 1 to n. dp[i] represents the number of unique BSTs possible with i nodes, computed by trying every value as the root and multiplying the number of valid left-subtree shapes by the number of valid right-subtree shapes — this sequence is famously known as the Catalan numbers.
How Unique BSTs Works
- Define dp[i] as the number of unique BSTs that can be formed with i nodes. Base cases: dp[0] = 1 (an empty tree) and dp[1] = 1 (a single node).
- For each count of nodes i from 2 to n, try every value from 1 to i as the root of the tree.
- If value k is the root, then k-1 values go into the left subtree and (i-k) values go into the right subtree.
- The number of trees for this choice of root is dp[k-1] (left subtree shapes) multiplied by dp[i-k] (right subtree shapes) — add this product to dp[i].
- After trying every possible root value, dp[i] holds the total count of unique BSTs for i nodes; return dp[n].
Unique BSTs Worked Example
Input: 3
dp[0]=1, dp[1]=1. dp[2]=dp[0]×dp[1] + dp[1]×dp[0] = 1+1=2. dp[3]: root=1→dp[0]×dp[2]=1×2=2; root=2→dp[1]×dp[1]=1×1=1; root=3→dp[2]×dp[0]=2×1=2. Sum: 2+1+2=5. Number of unique BSTs with 3 nodes: 5.
| 0 | 1 | |
|---|---|---|
| dp | 1 | 1 |
def num_trees(n):
dp = [0] * (n + 1)
dp[0] = 1
for i in range(1, n + 1):
for j in range(i):
dp[i] += dp[j] * dp[i - 1 - j]
return dp[n]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Unique BSTs Time & Space Complexity
When to Use Unique BSTs
- Combinatorics problems counting valid tree/bracket/parenthesization structures — the Catalan number sequence appears in many similar counting problems (like Generate Parentheses).
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.