Unique Binary Search Trees solution explained

The number of structurally different binary search trees on the keys 1 to n is the nth Catalan number. Compute it with dynamic programming: if ways[k] counts trees with k nodes, then ways[n] is the sum over every choice of root of ways[left size] × ways[right size], which takes O(n²) time and O(n) space. A closed form, C(2n, n) / (n + 1), gives the same value in O(n) arithmetic steps.

By Published 7 min read

The question

You are given a positive integer n. Count how many binary search trees exist whose nodes are exactly the values 1, 2, ..., n, each used once, where two trees count as different if their shapes differ. In a binary search tree every key in a node's left subtree is smaller than the node and every key in its right subtree is larger, so once the shape is fixed, the placement of the values is forced. Counting trees and counting shapes are the same thing.

Counts for small n, computed for this page
nNumber of treesQuick reason
11A single node
22Root 1 with 2 on the right, or root 2 with 1 on the left
35Root 1 gives 2 shapes, root 2 gives 1, root 3 gives 2
4145 + 2 + 2 + 5, one term per root
6132Grows fast: roughly 4^n divided by a polynomial
Counts for small n, computed for this page. Scroll sideways on a small screen.

The row for n = 4 shows the counting rule. With root 1, the left side is empty (1 way) and the right side has three keys (5 ways), so 5. Root 2: one key on the left, two on the right, 1 × 2 = 2. Root 3 mirrors root 2, and root 4 mirrors root 1. Total 5 + 2 + 2 + 5 = 14. Before coding, confirm with the interviewer that only the count is wanted. Producing the trees themselves is a different problem, covered in Unique Binary Search Trees II.

Slow approach: recurse over every root

Turn the counting rule into a function count(lo, hi) for the keys lo to hi. An empty range or a single key has exactly one tree. Otherwise, try each key as the root and multiply the counts of the two sides. This is correct, but the same ranges are recounted over and over, and the running time grows exponentially, about as fast as the Catalan numbers themselves.

def count_bsts_slow(n):
    def count(lo, hi):
        if lo >= hi:  # empty range or a single key
            return 1
        return sum(count(lo, root - 1) * count(root + 1, hi)
                   for root in range(lo, hi + 1))

    return count(1, n)
Direct recursion: exponential time.

Notice the first observation that unlocks the fast version: count(3, 5) and count(7, 9) are the same number, because only the size of a range matters, not its keys. That shrinks the state from a pair (lo, hi) to a single size.

Main approach: dynamic programming over sizes

Let ways[k] be the number of BST shapes with k nodes. An empty tree counts as one shape, so ways[0] = 1. For a tree of size s, choose how many nodes go to the left subtree, call it left, from 0 to s − 1; the root takes one node and the right subtree gets s − 1 − left. Each left shape pairs with each right shape, so ways[s] is the sum of ways[left] × ways[s − 1 − left]. Fill sizes in increasing order so both factors are ready when you need them.

def count_bsts(n):
    ways = [0] * (n + 1)
    ways[0] = 1  # the empty tree
    for size in range(1, n + 1):
        for left in range(size):  # nodes in the left subtree
            ways[size] += ways[left] * ways[size - 1 - left]
    return ways[n]
Python: bottom-up over subtree sizes, O(n²) time and O(n) space.
function countBsts(n) {
  const ways = new Array(n + 1).fill(0);
  ways[0] = 1;
  for (let size = 1; size <= n; size++) {
    for (let left = 0; left < size; left++) {
      ways[size] += ways[left] * ways[size - 1 - left];
    }
  }
  return ways[n];
}
JavaScript: same table. Exact while the count stays below 2^53 (n up to 30).

Run the table for n = 3. ways[1] = ways[0] × ways[0] = 1. ways[2] = ways[0] × ways[1] + ways[1] × ways[0] = 2. ways[3] = 1 × 2 + 1 × 1 + 2 × 1 = 5. Three short lines, and each one reads entries that were already final.

The closed form

The recurrence above defines the Catalan numbers, which have the formula C(2n, n) / (n + 1), the central binomial coefficient divided by n + 1. With Python's math.comb that is a single line, and it is fine to mention after you have derived the DP. Most interviewers care more about the derivation than the formula, so lead with the recurrence and bring up Catalan as the name for what you found.

from math import comb

def count_bsts_formula(n):
    return comb(2 * n, n) // (n + 1)
Python: the Catalan formula, exact with big integers.

Complexity

Cost of computing the count for n keys
ApproachTimeExtra space
Recursion over (lo, hi)Exponential, Catalan-like growthO(n) stack
Memoized recursion over sizeO(n²)O(n)
Bottom-up tableO(n²)O(n)
Binomial formulaO(n) multiplications on growing integersO(1) beyond the integers
Cost of computing the count for n keys. Scroll sideways on a small screen.

Edge cases and limits

  • n = 0: the code returns 1, the empty tree. Some statements start at n = 1; ask which answer is expected.
  • n = 1 returns 1. Check it explicitly, since off-by-one errors in the inner loop often show up here first.
  • Integer size: the count for n = 19 is 1,767,263,190, which still fits a signed 32-bit int; n = 20 does not. A signed 64-bit int holds up to n = 35.
  • JavaScript numbers stay exact through n = 30. Beyond that, switch the table to BigInt.

Common mistakes

  • Setting ways[0] = 0. An empty subtree is one valid choice, and zero there wipes out every product that uses it.
  • Adding the left and right counts instead of multiplying them. Every left shape combines with every right shape.
  • Keeping the state as (lo, hi) and building an n × n table. It works, but it hides the insight that only size matters and does extra work.
  • Quoting the formula without being able to explain it. Interviewers usually follow up with "why does that hold?"
  • Assuming the problem wants distinct value orders rather than shapes. In a BST, the shape fixes where every value goes.

How to present it

Fictional example

Deriving the recurrence out loud
Candidate
If I fix the root as r, the BST property forces keys 1 to r − 1 into the left subtree and r + 1 to n into the right. Those subtrees are independent, so the number of trees with root r is the product of the two counts.
Candidate
The count only depends on how many keys a subtree has, so I'll keep ways[k] for k nodes, with ways[0] = 1, and sum over all left sizes for each total size.
Candidate
That's O(n²) time and O(n) space. These are the Catalan numbers, so there's also a binomial formula if you want it.

Where to go next

The same "pick the top-level split, multiply or combine the two sides" structure drives Unique Binary Search Trees II, which builds the actual trees, and Different Ways to Add Parentheses, where the split is an operator instead of a root. If you came here from simpler one-dimensional DP, Tribonacci Number is the warm-up. For broader tree topics, see data structure interview questions.

Natively during prep

Counting problems reward writing the recurrence before the code. In practice, Natively can read a problem from a screenshot and suggest an approach you can check against your own derivation, and it keeps a transcript of spoken mock rounds on your computer, which helps you hear whether your explanation of "why multiply" was actually clear. The AI interview assistant page explains the setup.

Questions people ask

How do you count unique binary search trees for n keys?

Let ways[k] be the number of shapes with k nodes, with ways[0] = 1. For each size, sum ways[left] × ways[size - 1 - left] over every possible left subtree size. ways[n] is the answer, in O(n²) time.

Why are the counts multiplied rather than added?

Once the root is fixed, the left and right subtrees are chosen independently, and every left shape can pair with every right shape. The number of pairs is the product of the two counts.

What are the Catalan numbers and how do they relate?

The Catalan numbers 1, 1, 2, 5, 14, 42, ... satisfy exactly this recurrence. The nth one equals C(2n, n) / (n + 1) and is the number of BST shapes on n keys.

How many unique BSTs are there for n = 3?

Five. Root 1 allows two shapes on its right, root 2 allows one, and root 3 allows two on its left.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP