Optimal Binary Search Tree

Pattern: Partition and interval DP

hard

Keys are sorted; a key at depth d costs freq × d. dp[i][j] is the least cost for keys i..j-1; try each as the root, and every key in the segment goes one level deeper, adding the segment's total frequency.

The problem

Given sorted keys and their search frequencies, build a binary search tree that minimises the sum of freq[i] × depth(i) (the root has depth 1). Return that sum.

Think first

  • What does choosing a root do to the other keys?
  • How much does going one level deeper add?
  • What are the subproblems?

Hints

    Brute force, and why it fails

    Try every tree shape: Catalan-many.

    The key insight

    Each subtree holds a contiguous segment, and the depth shift is just the segment's frequency sum.

    Dry run

    keys [10, 12], freq [34, 50]. Root 12: 50 × 1 + 34 × 2 = 118.

    Step 1 of 2

    The plan

    dp[i][j] = sum(freq[i..j-1]) + min over r of dp[i][r] + dp[r + 1][j]
    

    Complexity

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

    Segments times roots.

    Edge cases

    • One key: its frequency.
    • Equal frequencies.
    • One very frequent key.
    I've built my logic, show the code

    Java

    class Solution {
        public int optimalSearchTree(int[] keys, int[] freq) {   // keys sorted; a key at depth d costs freq × d
            int n = keys.length;
            int[] pre = new int[n + 1];
            for (int i = 0; i < n; i++) pre[i + 1] = pre[i] + freq[i];
            int[][] dp = new int[n + 1][n + 1];     // dp[i][j]: the least cost for keys i .. j - 1
            for (int len = 1; len <= n; len++)
                for (int i = 0; i + len <= n; i++) {
                    int j = i + len;
                    dp[i][j] = Integer.MAX_VALUE;
                    for (int r = i; r < j; r++)     // key r is the root; every key below goes one level deeper
                        dp[i][j] = Math.min(dp[i][j], dp[i][r] + dp[r + 1][j]);
                    dp[i][j] += pre[j] - pre[i];
                }
            return dp[0][n];
        }
    }

    C++

    class Solution {
    public:
        int optimalSearchTree(vector<int>& keys, vector<int>& freq) {   // keys sorted; a key at depth d costs freq × d
            int n = static_cast<int>(keys.size());
            vector<int> pre(n + 1, 0);
            for (int i = 0; i < n; i++) pre[i + 1] = pre[i] + freq[i];
            vector<vector<int>> dp(n + 1, vector<int>(n + 1, 0));   // dp[i][j]: the least cost for keys i .. j - 1
            for (int len = 1; len <= n; len++)
                for (int i = 0; i + len <= n; i++) {
                    int j = i + len;
                    dp[i][j] = INT_MAX;
                    for (int r = i; r < j; r++)     // key r is the root; every key below goes one level deeper
                        dp[i][j] = min(dp[i][j], dp[i][r] + dp[r + 1][j]);
                    dp[i][j] += pre[j] - pre[i];
                }
            return dp[0][n];
        }
    };

    Python

    class Solution:
        def optimalSearchTree(self, keys: list[int], freq: list[int]) -> int:   # a key at depth d costs freq × d
            n = len(keys)
            pre = [0]
            for f in freq:
                pre.append(pre[-1] + f)
            dp = [[0] * (n + 1) for _ in range(n + 1)]   # dp[i][j]: the least cost for keys i .. j - 1
            for length in range(1, n + 1):
                for i in range(n - length + 1):
                    j = i + length                  # key r is the root; every key below goes one level deeper
                    dp[i][j] = min(dp[i][r] + dp[r + 1][j] for r in range(i, j)) + pre[j] - pre[i]
            return dp[0][n]

    Common mistakes

    • Forgetting the frequency sum for the depth shift.
    • Making the root depth 0.

    Similar problems