← All problemsFree · Python · 50 min

Algorithm design / guarantees under an adversary

The Dictionary Shelf

Given how often each key is looked up, build the binary search tree with the fewest total comparisons. See why putting the most popular key at the root fails, then write the dynamic program and return the tree itself.

0 / 3 graded parts passSaved in this browser · loading saved work…
Jump to your work ↓

A translation office keeps its glossary in a binary search tree. Each lookup compares the wanted word with a key, and goes left or right until it finds the word. The office knows how often each word is looked up, so it wants the tree with the fewest comparisons in total.

keys 0 to 3, looked up 2, 3, 4, 1 times0×21×32×43×1keydepthf×depth0241132312322total 21parent list: [1, -1, 3, 1]
One tree and its cost. Not the best one, necessarily.

The keys are 0,1,…,n−1 in sorted order, and key i is looked up fi times. A lookup of a key at depth d makes d comparisons, with the root at depth 1. So a tree costs ∑ifi·depth(i).

A tree is written as a parent list: parent[i] is the key directly above key i, or −1 for the root. It must be a binary search tree: smaller keys to the left of each key, larger to the right.

Background: Dynamic Programming I.

easy · Part A

Four keys by hand

Four keys looked up 4,2,6,3 times. What is the fewest comparisons any binary search tree on them makes?

Explore in the sandbox

Experiment here, then copy a rule into the editor and test its guarantees.