Problem 96

Abstract / Summary

Given a number of nodes find how many different binary search trees can be made with them

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0096.cpp

class Solution {
public:
    int numTrees(int n) {
        // problem 95 identified this as Catalan numbers
        // https://www.wolframalpha.com/input?i=1%2C2%2C5%2C14%2C42%2C132%2C429
        vector<int64_t> result =
        {
            1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845, 35357670, 129644790, 477638700, 1767263190, 6564120420, 24466267020, 91482563640, 343059613650, 1289904147324, 4861946401452, 18367353072152, 69533550916004, 263747951750360 };

        return result[n - 1];

    }
}
13 lines | 560 bytes | submitted August 8, 2023 | GitHub   22% comment ratio | tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 64% (1+ million submissions).

Typical patterns to solve this problem:
  • Binary Search Tree
  • Binary Tree
  • Dynamic Programming
  • Math
  • Tree
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single public method numTrees. The method computes the number of distinct binary search trees that can be formed with n distinct keys. Rather than calculating the value dynamically, it stores a pre-computed sequence of Catalan numbers in a vector<int64_t> and returns the element that corresponds to the requested size.

Core Logic

The heart of the algorithm is the static lookup table. The vector is initialized with a literal list of Catalan numbers ranging from the first value (for n = 1) up to the twenty-eighth value (for n = 28). The method accesses the element at index n-1 and returns it directly.

vector<int64_t> result = {
    1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796,
    58786, 208012, 742900, 2674440, 9694845, 35357670,
    129644790, 477638700, 1767263190, 6564120420,
    24466267020, 91482563640, 343059613650, 1289904147324,
    4861946401452, 18367353072152, 69533550916004,
    263747951750360
};

The return statement extracts the appropriate entry:

return result[n - 1];

Edge Cases Handled

The function implicitly handles the smallest valid input (n = 1). In this case the index calculation n-1 yields zero, and the first element of the vector (1) is returned, which correctly represents the single possible BST for one node. Because the vector is sized to contain entries for n up to 28, any call with n in the range [1, 28] will safely index the vector without out-of-bounds access. The use of a 64-bit integer type (int64_t) accommodates the large values that appear in the later part of the sequence, preventing overflow for the supported range.

Performance Optimizations

The most significant optimization is the elimination of any runtime computation. By storing the Catalan numbers ahead of time, the method reduces the work to a constant-time array access and a single subtraction for the index. This yields an O(1) execution path regardless of the input size. The vector is constructed once per call, but because the initializer list is a compile-time constant, modern compilers can place the data in read-only memory, effectively treating it as a static array. This avoids dynamic memory allocation and the overhead of iterative or recursive Catalan number formulas. The choice of int64_t ensures that the values fit within the native word size of most 64-bit architectures, allowing the processor to handle arithmetic and memory operations efficiently.

Overall, the implementation provides an immediate answer for any supported n with minimal computational expense.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big box of special building blocks. These blocks are very clever because they know exactly how to fit together to build many different tree shapes. Some shapes are tall and skinny like a pine branch, while others are short and wide like a bushy oak.

The code looks at a secret list that was written down by a very smart person. This list tells us exactly how many different ways those building blocks can be arranged. If you want to know how many trees you can build, you just tell the computer how many blocks you have. The code looks at the number you give it, finds that number in its secret list, and shows you the answer written right next to it. It is like having a magic book that tells you all the possible ways to build your tree garden before you even start playing.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 5 | μ = 5.63 | σ = 2.84

Complexity Analysis

Time: constant
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python C# Java Rust Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows Python
charles-wangkai Java
chenyanzhe C++
everthis JS
fartem Ruby
FelixFan1122 C#
fpdjsns C++
gaosq0604 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
martianoff Scala
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
wisdompeak C++
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows Python, Python
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fpdjsns C++
gaosq0604 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
martianoff Scala
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
wisdompeak C++
zfang399 C++
53 links | 37 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Unique Binary Search Trees | Count all structurally unique BSTs | Catalan number | Leetcode #96'
Techdose 8 mins
Unique Binary Search Trees | Count all structurally unique BSTs | Catalan number | Leetcode #96
YouTube video 'Count Unique Binary Search Trees | LeetCode 96 | C++, Java, Python | Catalan Number'
Knowledge Center 17 mins
Count Unique Binary Search Trees | LeetCode 96 | C++, Java, Python | Catalan Number
YouTube video '[Leetcode 96] Unique Binary Search Tree'
basketwangCoding 8 mins
[Leetcode 96] Unique Binary Search Tree
YouTube video 'Unique Binary Search Trees II | LeetCode 95 | Theory + Python code'
Sai Anish Malla 20 mins
Unique Binary Search Trees II | LeetCode 95 | Theory + Python code
YouTube video 'Leetcode - Unique Binary Search Trees (Python)'
Timothy H Chang 10 mins
Leetcode - Unique Binary Search Trees (Python)
YouTube video 'unique binary search trees | unique binary search trees leetcode | leetcode 96 | recursive | top dow'
Naresh Gupta 12 mins
unique binary search trees | unique binary search trees leetcode | leetcode 96 | recursive | top dow
YouTube video 'Dp on Trees | Unique Binary Search Trees | Leetcode 96 | Live coding sessionšŸ”„ | Dynamic Programming'
Coding Decoded 12 mins
Dp on Trees | Unique Binary Search Trees | Leetcode 96 | Live coding sessionšŸ”„ | Dynamic Programming
YouTube video 'LeetCode 96. Unique Binary Search Trees'
Happy Coding 20 mins
LeetCode 96. Unique Binary Search Trees
YouTube video 'Leetcode Question 96. Unique Binary Search Trees Solution (With Code In Java)'
Alex Solves Algorithms 8 mins
Leetcode Question 96. Unique Binary Search Trees Solution (With Code In Java)
YouTube video 'Attempting Leetcode (Question 96: Unique Binary Search Trees)'
Mykola 19 mins
Attempting Leetcode (Question 96: Unique Binary Search Trees)
YouTube video 'Daily Leetcode #587: Nov 08, 2021 - 96. Unique Binary Search Trees'
Programming Live with Larry 10 mins
Daily Leetcode #587: Nov 08, 2021 - 96. Unique Binary Search Trees
YouTube video 'Daily Leetcode #85: Jun 24, 2020 - 96. Unique Binary Search Trees'
Programming Live with Larry 9 mins
Daily Leetcode #85: Jun 24, 2020 - 96. Unique Binary Search Trees
YouTube video 'LeetCode 96 | Unique Binary Search Trees | DP | Recursive Memoization | Debugger | Java'
Sleepy Cracker 15 mins
LeetCode 96 | Unique Binary Search Trees | DP | Recursive Memoization | Debugger | Java
YouTube video 'LeetCode 96. Unique Binary Search Trees'
Education, the study of everything 8 mins
LeetCode 96. Unique Binary Search Trees
YouTube video 'Leetcode Question 96 "Unique Binary Search Trees" in Javascript'
Ghumman Tech 6 mins
Leetcode Question 96 "Unique Binary Search Trees" in Javascript
YouTube video 'No Sound Leetcode 96: Unique Binary Search Trees'
ExtremeProgrammer 3 mins
No Sound Leetcode 96: Unique Binary Search Trees
YouTube video 'leetcode 96. Unique Binary Search Trees - DP or Catalan Number'
Code-Yao 10 mins
leetcode 96. Unique Binary Search Trees - DP or Catalan Number
YouTube video 'Day 355: LeetCode Problem 96. Unique Binary Search Trees - Swift'
iOSxBank 9 mins
Day 355: LeetCode Problem 96. Unique Binary Search Trees - Swift
18 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

19 easy 42 medium 2 hard
64 solutions   August 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality