Unique Binary Search Trees

Medium Dynamic Programming 1D DP Original on LeetCode

Reported atSwiggy

Unique Binary Search Trees is a medium dynamic programming problem solved with the 1d dp pattern. The best approach, optimal (catalan number formula), runs in O(n) time and O(1) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (plain recursion) up.

Problem

You are given an integer n. Count how many structurally different binary search trees can be built that contain exactly the values 1, 2, ..., n, each used once.

Two trees are different if their shapes differ (the values are then forced by the BST ordering). Return that count.

Examples

Example 1

Input
n = 2
Output
2
Why
Either 1 is the root with 2 as its right child, or 2 is the root with 1 as its left child.

Example 2

Input
n = 4
Output
14
Why
Roots 1, 2, 3, 4 give 5 + 2 + 2 + 5 = 14 trees (left count × right count for each root).

Example 3

Input
n = 1
Output
1
Why
A single node is the only possible tree.

Constraints

  • 1 <= n <= 19
  • The answer fits in a 32-bit signed integer.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 11 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (plain recursion)O(3ⁿ)O(n)
Bottom-up DPO(n²)O(n)
Optimal (Catalan number formula)O(n)O(1)

1Brute force (plain recursion)

TimeO(3ⁿ)The same subproblem sizes are recomputed again and again; the call count roughly triples with each extra node.
SpaceO(n)Recursion depth is at most n.

Try every value as the root. The smaller values form the left subtree and the larger ones the right subtree, and each side is counted recursively. Multiply the two counts and add over all roots.

  1. count(k) = 1 when k <= 1 (empty tree or one node).
  2. Otherwise, for each root position r from 1 to k, add count(r - 1) * count(k - r).
  3. Return count(n).
class Solution {
    public int numTrees(int n) {
        return count(n);
    }

    private int count(int k) {
        if (k <= 1) return 1;
        int total = 0;
        for (int r = 1; r <= k; r++) {
            total += count(r - 1) * count(k - r);
        }
        return total;
    }
}

2Bottom-up DP

TimeO(n²)For each of the n sizes we try up to n root positions.
SpaceO(n)The table has n + 1 entries.

Let G[k] be the number of distinct BSTs with k nodes. Because only the size matters, G[k] is the sum over every root position r of G[r - 1] * G[k - r]. Compute the table from small sizes to large.

  1. Create G of size n + 1 with G[0] = G[1] = 1.
  2. For k from 2 to n, for r from 1 to k, add G[r - 1] * G[k - r] to G[k].
  3. Return G[n].
class Solution {
    public int numTrees(int n) {
        int[] g = new int[n + 1];
        g[0] = 1;
        g[1] = 1;
        for (int k = 2; k <= n; k++) {
            for (int r = 1; r <= k; r++) {
                g[k] += g[r - 1] * g[k - r];
            }
        }
        return g[n];
    }
}

3Optimal (Catalan number formula)

TimeO(n)One multiplication and one division per step, n steps.
SpaceO(1)Only a single running value.

The table from the DP is the sequence of Catalan numbers, which satisfy C(i + 1) = C(i) * 2(2i + 1) / (i + 2). Start from C(0) = 1 and apply this step n times. Use a 64-bit integer so the multiplication before the division cannot overflow; the division is always exact.

  1. Set c = 1 (a long).
  2. For i from 0 to n - 1: c = c * 2 * (2i + 1) / (i + 2).
  3. Return c as an int.
class Solution {
    public int numTrees(int n) {
        long c = 1;
        for (int i = 0; i < n; i++) {
            c = c * 2 * (2 * i + 1) / (i + 2);
        }
        return (int) c;
    }
}

Edge cases to test

  • n = 1: exactly one tree
  • n = 19: the largest answer, 1767263190, still fits in an int but intermediate products in a formula may not
  • An empty subtree counts as one way, not zero

Hints

Hint 1

Pick the root value r. Which values must go to the left subtree, and which to the right?

Hint 2

The shape count only depends on how many nodes a subtree has, not on which values they are. If G(k) is the count for k nodes, then root r contributes G(r - 1) × G(n - r).

Hint 3

Fill G from 0 up to n, with G(0) = G(1) = 1.

FAQ

What is the best time complexity for Unique Binary Search Trees?

Optimal (Catalan number formula) runs in O(n) time and O(1) extra space. One multiplication and one division per step, n steps.

Which pattern does Unique Binary Search Trees use?

It is a dynamic programming problem that uses the 1d dp pattern. Other problems with the same pattern: Fibonacci Number, Climbing Stairs, Min Cost Climbing Stairs (2 jumps).

Is there a brute force solution for Unique Binary Search Trees?

Yes. Brute force (plain recursion) takes O(3ⁿ) time and O(n) space. Try every value as the root.

Which edge cases should I test for Unique Binary Search Trees?

n = 1: exactly one tree; n = 19: the largest answer, 1767263190, still fits in an int but intermediate products in a formula may not; An empty subtree counts as one way, not zero.