Optimal Binary Search Tree (OBST) in DAA with Solved Example and Code

Overview
An optimal binary search tree is a binary search tree built so that the total expected cost of searching it is as low as possible. Each key has a known search probability, and the tree is arranged to place frequently searched keys nearer the root. It is built with dynamic programming in O(n³) time.
Say you have a fixed set of keys, sorted, and you already know roughly how often each one gets searched. What shape should the tree take? That question is the entire optimal binary search tree (OBST) problem. It shows up constantly in DAA courses because the answer isn't intuitive: you don't balance the tree, you compute it, key by key, with dynamic programming, and the result deliberately looks lopsided sometimes. This page works through a full solved example with every intermediate table, a corrected variant with dummy keys, three practice problems with answers, and working code in C++, Java and Python, plus the O(n²) speedup almost no other page mentions.
What Is an Optimal Binary Search Tree?
An optimal binary search tree is a binary search tree built for a known set of keys and their search probabilities, arranged so that the expected number of comparisons per search is as small as possible. Frequently searched keys sit nearer the root, rarely searched keys sit deeper. It's built with dynamic programming, not by balancing.
The inputs are the sorted keys and a probability for each one. "Cost" here means the expected number of comparisons per search, weighted by how often each key is actually looked up, not the tree's height and not its balance. That's the one-line insight worth holding onto: the algorithm decides what "near the root" means by arithmetic, on the actual probabilities, not by any structural rule the way binary search trees and other core data structures usually get balanced.
Why Is It Called "Optimal"?
Because it achieves the lowest possible expected search cost among every valid BST on those keys, not because it's balanced and not because it's fast to build. For 4 keys there are 14 distinct BSTs to choose from (the 4th Catalan number). For 15 keys, that's 9,694,845 trees. "Optimal" refers to that minimum found among all of them, nothing else.
Let’s take an example for better understanding:
Let’s assume that we have the following keys in our tree: 15, 25, 35, 45, 55, 65, 75

The maximum time required to search a node in a binary search tree is equal to the minimum height of the tree i.e. logn.
If we have keys: 15, 25, 35, then see how many BST can be formed. We will use the formula given below:
=
So we can see that 5 trees will be formed as shown in the figure given below.

Avg. number of comparisons:

Avg no of comparisons


Avg no of comparisons

Avg no of comparisons
In the third case, the total number of comparisons is less as compared to others because the height of the tree is less. So we can say that it’s a balanced binary search tree.
Build an AI-First Career, Master the Complete Skillset
Choose from our industry-leading programs designed for career success
Modern Software and AI Engineering Program
Master full-stack development with AI integration
+1000 moreModern Data Science and ML with specialisation in AI
Advanced data science techniques with AI specialization
+1000 moreAdvanced AIML with Specialisation in Agentic AI
Deep dive into AIML with focus on Agentic systems
+1000 moreDevOps, Cloud & AI Platform Engineering
Build and manage AI-powered cloud infrastructure
+1000 moreAI Engineering Advanced Certification by IIT-Roorkee
Premier AI engineering certification from IIT-Roorkee
AI Forward Deployed Engineer Program
Full-stack engineering, production AI and client-facing consulting
+1000 moreMathematical Formulation
- The keys in the OBST are in the sorted order ki……..kj, where 1<=i<=j<=n.
- The subtree containing keys ki….kj, has leaves with dummy keys di-1……dj.
- Suppose kr is the root of the subtree containing keys ki………kj. So the left subtree of the root kr has the keys ki……kr-1 and the right subtree contains keys kr+1 to kj.
- Let’s assume e[i, j] represents the expected cost of searching OBST. With n keys, our aim is to find and minimize e[1, n].
- The base case occurs when j = i – 1, because we just have the dummy key di-1 for this case. For this case, the expected search cost is e [i, j] = e [i, i - 1] = qi-1.
- For the case, j ≥ i, we have to select any key kr from ki…kj as a root of the tree.
- With kr as a root key and sub tree ki…kj, the sum of probability is defined as:
Recursive formula for forming a OBST is given below:
Algorithm
First, we construct a BST from a set of n distinct keys <k1, k2, k3,... kn >. Here we assume, the probability of accessing a key Ki is pi. Some dummy keys (d0, d1, d2, ... dn) are added as some searches may be performed for the values which are not present in the Key set K. We assume, for each dummy key, di probability of access is qi.
Algorithm for finding optimal tree for sorted, distinct keys ki…kj:
- For each possible root, kr for i≤r≤ji≤r≤j
- Make optimal subtree for ki,…,kr−1.
- Make optimal subtree for kr+1,…,kj.
- Select a root that gives the best total tree.
Complexity Analysis of Optimal Binary Search Tree
We can easily derive the complexity of the above algorithm. We can see that it has three nested loops. The innermost loop statements run in Q(1) time.
The above algorithm runs in Cubic time.
Example
Let p (1 : 3) = (0.5, 0.1, 0.05) q(0 : 3) = (0.15, 0.1, 0.05, 0.05) Compute and construct OBST for above values using Dynamic approach.
Recursive Formula to solve :
where,
mitially,










Types
Optimal BST is divided into two types:
Static Optimality:
In the static optimality problem, the tree can’t be modified after it has been constructed. In this instance, a specific configuration of the tree's nodes offers the shortest predicted search time for the specified access probabilities.
Dynamic Optimality:
In the dynamic optimality problem, the tree can be modified at any time by tree rotations. In the tree, the cursor is pointing at the root node so that it can move or perform modifications. The cursor in this case visits each node in the target access sequence sequentially thanks to some low-cost sequence of these operations.
How to Solve Optimal Binary Search Tree (with Implementation Code and Complexity Analysis)
We have given a sorted array of keys, which consists of keys to be searched and a frequency array of frequency counts.
We have to construct a binary search tree such that the total cost of all the searches is as small as possible. First we will calculate the cost, but how to calculate the cost?
"Cost is the level of that node multiplied by frequency."
Let's take an example to understand it properly:
Now, we see the recusrive and dynamic programming code to find the cost of optimal BST.
How Scaler Transformed Careers in Different Fields
Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L.
Using Recursive Approach
The plan is to try each node as root one at a time (r varies from i to j in the second term). Making the rth node the root allows us to determine the optimal cost from i to r-1 and r+1 to j recursively.
The frequencies from i to j are summed (see first term in the above formula).
C++
Output:
Java
Output:
Python
Output:
Complexity Analysis:

The basic recursive technique described above has exponential time complexity. It should be noted that the above function repeatedly computes the same subproblems. In the recursion tree for frequency [1...4], we can see that several subproblems are being repeated. Since the same problem is repeated again and again, this problem has the overlapping subproblem property.
Using Dynamic Programming
We use an auxiliary array cost[n][n] to store the solutions of subproblems. cost[0][n-1] will hold the final result. The challenge is that all diagonal values must be filled first, then the values that lie on the line just above the diagonal. Or in a simple way, we need to first fill in all the cost[i][i] values, then all the cost[i][i+1] values, and finally all the cost[i][i+2] values.
C++
Output:
Java
Output:
Python
Output:
Complexity Analysis:
Time complexity:
The above solution has an time complexity. By precalculating the sum of frequencies rather than continuously calling the add() function, the time complexity can be easily reduced to .
Space Complexity:
The above solution has an space complexity since we are making a 2D array.
Conclusion
Let's conclude our topic on optimal binary search trees by mentioning some of the most important points:
- An optimal binary search tree is a binary search tree that provides the shortest possible search time or expected search time and it is also known as a weight-balanced search tree.
- The cost of searching for a node in the tree plays a vital role, and it is decided by the frequency and key value of the node.
- Optimal BST is divided into two types: Static Optimality and Dynamic Optimality.
- The basic recursive technique has exponential time complexity. It should be noted that the optCost function repeatedly computes the same subproblems.
- In dynamic programming approach, by precalculating the sum of frequencies rather than continuously calling the add() function, the time complexity can be easily reduced to .
Turn Learning into Career Growth
Key Takeaways
- Use an optimal BST when the keys are fixed and reliable access probabilities are available.
- Use a balanced BST when worst-case height matters more than a known access distribution.
- Use memoisation or bottom-up DP to avoid recomputing overlapping subproblems.
- Keep the root table: it turns the minimum cost into a reconstructable tree.
- Do not treat the static OBST as a structure to update freely when keys or access frequencies change; rebuilding may be necessary.
FAQs
What is an optimal binary search tree?
An optimal binary search tree is arranged to minimise the expected number of comparisons for a known set of key-search and unsuccessful-search probabilities. Dynamic programming evaluates possible roots for each interval, stores the minimum cost and records the selected root so the final tree can be reconstructed.
How is an optimal BST different from a balanced BST?
A balanced BST controls its height to keep worst-case search depth small, without requiring known access frequencies. An optimal BST uses known successful and unsuccessful search probabilities to minimise expected search cost. It may be unbalanced when a few keys are searched much more frequently than others.
What is the time complexity of the optimal BST algorithm?
The standard bottom-up dynamic programming algorithm takes O(n³) time with precomputed cumulative weights and O(n²) space. Knuth's root monotonicity optimisation can reduce the time to O(n²) under the standard optimal-BST assumptions, while retaining O(n²) space.
Why is dynamic programming used for this problem?
The problem has optimal substructure because the left and right subtrees of an optimal tree must themselves be optimal for their key intervals. It also has overlapping subproblems because the same intervals are considered under different root choices. Dynamic programming stores each interval result instead of solving it repeatedly.
What do the dummy nodes q₀…qₙ represent?
Dummy nodes represent unsuccessful searches. Each qᵢ is the probability that a search falls between two adjacent keys, or before the first or after the last key. They are included because an optimal search tree must account for both successful and unsuccessful searches when calculating expected cost.
Can an optimal BST be updated after it is built?
The static optimal-BST solution is computed for a fixed key set and probability distribution. If keys or access frequencies change, the old tree may no longer be optimal and may need to be rebuilt. Self-adjusting trees such as splay trees address changing access patterns, but they are a different model.