Skip to problem
←

Optimal Binary Search Tree

Hard 0 attempts

Given two equal-length arrays, keys and freq, construct a binary search tree containing every key exactly once. The keys are distinct and already sorted in increasing order; freq[i] is the search frequency of keys[i].

A key's search cost is its frequency multiplied by its level, with the root at level 1, its children at level 2, and so on. The total cost is the sum over all keys. Only searches for the supplied keys contribute to the cost; there are no costs for unsuccessful searches.

Choose a tree shape that preserves the binary search tree ordering and minimizes the total cost. Return that minimum cost, not the tree. Keys with zero frequency must still be included.

For keys = [10, 12, 20] and freq = [34, 8, 50], an optimal tree has root 20, its left child 10, and 10's right child 12. Its cost is 50 × 1 + 34 × 2 + 8 × 3 = 142.

Function contract

Implement optimalBST(keys, freq).

Output: Return the minimum sum of frequency × level over every key, with root level 1.

Example 1

Input
keys = [10,12,20]
freq = [34,8,50]
Output
142

Example 2

Input
keys = [10]
freq = [5]
Output
5
Visual Aid
An optimal tree for the first example
Optimal search tree with total cost 142Root 20 at level 1 has left child 10 at level 2. Node 10 has right child 12 at level 3. Their weighted costs are 50, 68, and 24.201012Level 1 · 50 × 1 = 50Level 2 · 34 × 2 = 68Level 3 · 8 × 3 = 24

BST order determines where each key may go. A frequently searched key can be worth placing closer to the root.

Constraints
  • 1 <= keys.length == freq.length <= 50
  • Keys are distinct and sorted in increasing order.
  • Frequencies are non-negative integers, and the cost fits in a safe JavaScript integer.

Interval Dynamic Programming

Let dp[i][j] be the minimum search cost for keys in the inclusive interval [i, j], measured with that subtree's root at level 1. A single key costs its frequency; an empty interval costs zero.

Try each key r in the interval as its root. BST ordering fixes the left keys to [i, r - 1] and the right keys to [r + 1, j]. Attaching either subtree increases every key's level by one. Adding the sum of all frequencies in the interval accounts for those increases and the root's own level-1 cost:

cost = sum(freq[i..j]) + dp[i][r - 1] + dp[r + 1][j].

Take the smallest cost over all roots. Process shorter intervals first so both subproblems are ready. The key values themselves do not enter the cost calculation; their sorted order determines the allowed subtrees.

javascript
function optimalBST(keys, freq) {
  const n = keys.length;
  const dp = Array.from({ length: n }, () => Array(n).fill(0));
  for (let i = 0; i < n; i++) dp[i][i] = freq[i];
  for (let len = 2; len <= n; len++) {
    for (let i = 0; i + len - 1 < n; i++) {
      const j = i + len - 1;
      dp[i][j] = Infinity;
      let sum = 0;
      for (let k = i; k <= j; k++) sum += freq[k];
      for (let r = i; r <= j; r++) {
        const cost =
          sum + (r > i ? dp[i][r - 1] : 0) + (r < j ? dp[r + 1][j] : 0);
        dp[i][j] = Math.min(dp[i][j], cost);
      }
    }
  }
  return dp[0][n - 1];
}

Time: O(n³) | Space: O(n²)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript