Optimal BST Construction - Problem

Given an array of keys and their corresponding search frequencies, construct a Binary Search Tree that minimizes the total search cost.

The search cost for a key is defined as: frequency * (depth + 1), where depth is the level of the node in the BST (root has depth 0).

Your task is to return the minimum possible total search cost for the optimal BST.

Note: Keys are given in sorted order, and all frequencies are positive integers.

Input & Output

Example 1 — Basic Case
$ Input: keys = [10, 12, 20], frequencies = [34, 8, 50]
Output: 168
💡 Note: Optimal BST has key 20 as root (cost: 50×1=50), key 12 as left child (cost: 8×2=16), and key 10 as left child of 12 (cost: 34×3=102). Total: 50+16+102=168.
Example 2 — Two Keys
$ Input: keys = [10, 20], frequencies = [34, 50]
Output: 118
💡 Note: With two keys, optimal BST has key 20 as root (cost: 50×1=50) and key 10 as left child (cost: 34×2=68). Total: 50+68=118.
Example 3 — Equal Frequencies
$ Input: keys = [1, 2, 3], frequencies = [10, 10, 10]
Output: 40
💡 Note: With equal frequencies, optimal BST has key 2 as root (cost: 10×1=10), keys 1 and 3 as children (cost: 10×2 + 10×2=40). Total: 10+40=50.

Constraints

  • 1 ≤ keys.length ≤ 100
  • keys are sorted in ascending order
  • 1 ≤ frequencies[i] ≤ 100
  • keys.length == frequencies.length

Visualization

Tap to expand
INPUTKeys & Frequencies101220freq: 34freq: 8freq: 50Search Cost = frequency × (depth + 1)Goal: Minimize total search costby choosing optimal BST structureALGORITHMDynamic Programming1Create 2D DP table2Fill base cases (single keys)3Build up for larger ranges4Try each root, take minimumDP Table (partial)j=0 j=1 j=2i=034 50 168i=18 66RESULTOptimal BST Cost168Min CostOptimal Structure:201210Total: 50+16+102=168Key Insight:Dynamic programming finds optimal BST by building solutions from smaller subproblems,trying each possible root and combining optimal left and right subtree costs.TutorialsPoint - Optimal BST Construction | Dynamic Programming
Asked in
Google 25 Amazon 18 Microsoft 15 Meta 12
23.4K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen