Code RoomOptimal binary search tree
HardPrep Room Coding #1460

Optimal binary search tree

CodingAlgorithms & data structuresSenior–Staff~35 min

Given a sorted list of distinct keys with access frequencies 'freq' (freq[i] is how often key i is searched), build a binary search tree that minimizes the total expected search cost. The cost of an arrangement is the sum over all keys of freq[key] * (depth-of-key, counting the root as depth 1). Return the minimum possible total cost. 1 <= len(freq) <= 250, 0 <= freq[i] <= 10^5.

Implement
optimal_bst(freq: list[int]) → int
Examples
in[[34,8,50]]out142
What a strong answer looks like

State your approach and its time/space complexity out loud before you optimize. Handle the edge cases (empty input, duplicates, overflow), and say why you chose this over the brute force. Green tests are the floor, not the grade.

0:00 of about 35 min
InputExpectedGot
[[34,8,50]]142not run yetsample