Binary Search Trees in Lean Check a result Declarations Bibliography Lean source

Chapter 19Static search trees

A static tree never changes. It is built once, and then serves every request by an ordinary search from the root. Serving key xx costs one unit plus the depth of xx: this is StaticTree.cost, and Chapter 14 shows that it is exactly the cost of a pointer-machine execution that never rotates.

A static tree can know two things in advance: the number of keys, or how often each key will be requested. The first gives the balanced tree, which has the best possible worst-case guarantee. The second gives entropy trees and optimal trees, which are the benchmark behind static optimality. The two headline results are the worst-case baseline and the optimal tree:

Main result
A balanced tree pays at most 1+⌊log⁡2n⌋1 + \lfloor\log_2 n\rfloor per search, and no static tree does better in the worst case

The balanced tree on nn keys serves every sequence of mm searches at cost at most m(1+⌊log⁡2n⌋)m(1 + \lfloor\log_2 n\rfloor), counting one unit per search plus the depth of the requested key. Conversely, every tree on n≥1n \ge 1 keys has a key xx such that searching xx mm times costs at least m(1+⌊log⁡2n⌋)m(1 + \lfloor\log_2 n\rfloor).

In Lean, the balanced tree is Tree.balanced and the cost is StaticTree.cost. The repeated sequence is List.replicate m x.

The Lean statements
theoremClassical.Static.Results.balanced_costpropext · Classical.choice · Quot.soundClassical/Static/Abstract.lean:29
/-- Searching the balanced tree costs at most `1 + ⌊log₂ n⌋` per request. -/theorem balanced_cost (n : Nat) (xs : List Nat) (valid : ∀ x ∈ xs, x < n) :    StaticTree.cost (balanced n) xs ≤ xs.length * (Nat.log2 n + 1) := …  Static.balanced_cost n xs valid
theoremClassical.Static.Results.exists_expensivepropext · Classical.choice · Quot.soundClassical/Static/Abstract.lean:39
/-- No static tree does better in the worst case: repeating a deepest key `m`times costs at least `m(1 + ⌊log₂ n⌋)`. -/theorem exists_expensive (t : Tree) (h : 0 < t.size) (m : Nat) :    ∃ x < t.size, m * (Nat.log2 t.size + 1) ≤ StaticTree.cost t (List.replicate m x) := …  Static.exists_expensive t h m
5 definitions in 3 chapters · reading list
Main result · Knuth 1971; Yao 1980
The cost of an optimal static tree can be computed in O(n2)O(n^2) steps

For every sequence XX of requests to nn keys, the dynamic program builds a tree on the nn keys whose search cost for XX is at most that of every other tree on the same keys. Knuth’s algorithm computes this optimal cost while examining at most 2n22n^2 candidate roots; the library proves that it returns the cost, not that a tree built from its root table is optimal.

In Lean, the weights are the request counts Static.counts, the optimal tree and cost are Static.optTree and Static.optCost, and Knuth’s algorithm is Optimal.knuth, which returns the cost and the number of roots it examined.

The Lean statements
theoremClassical.Static.Optimal.Results.optTree_staticpropext · Classical.choice · Quot.soundClassical/Static/Optimal/Abstract.lean:92
theorem optTree_static (n : Nat) (xs : List Nat) (valid : ∀ x ∈ xs, x < n) :    (optTree (counts n xs)).size = n ∧      StaticTree.cost (optTree (counts n xs)) xs = optCost (counts n xs) := …  ⟨Static.optTree_counts_size n xs, Static.optTree_static n xs valid⟩
theoremClassical.Static.Optimal.Results.optCost_le_staticpropext · Classical.choice · Quot.soundClassical/Static/Optimal/Abstract.lean:97
theorem optCost_le_static (n : Nat) (xs : List Nat) (t : Tree) (ht : t.size = n)    (valid : ∀ x ∈ xs, x < n) : optCost (counts n xs) ≤ StaticTree.cost t xs := …  Static.optCost_le_static n xs t ht valid
theoremClassical.Static.Optimal.Results.knuth_optCostpropext · Classical.choice · Quot.soundClassical/Static/Optimal/Abstract.lean:78
theorem knuth_optCost (w : List Nat) : (knuth (rangeWeight w) w.length).1 = optCost w := …  Static.knuth_optCost w
theoremClassical.Static.Optimal.Results.knuth_steps_lepropext · Classical.choice · Quot.soundClassical/Static/Optimal/Abstract.lean:81
theorem knuth_steps_le (w : List Nat) : (knuth (rangeWeight w) w.length).2 ≤ 2 * w.length ^ 2 := …  Static.knuth_steps_le w
16 definitions in 3 chapters · reading list

19.1 Balanced trees

The library builds one balanced tree for every number of keys. The root takes the middle rank, and the larger half goes to the left:

defTree.balancedpropext · Quot.soundModels/Rotation/Abstract.lean:36
/-- The balanced tree on `n` keys. The root takes the middle rank; the leftsubtree gets `⌈(n-1)/2⌉` keys and the right subtree `⌊(n-1)/2⌋`, so the twosizes differ by at most one. -/def Tree.balanced : Nat → Tree  | 0 => .nil  | n + 1 => .node (balanced ((n + 1) / 2)) (balanced (n / 2))termination_by n => n

termination_by n => n tells Lean that the recursion terminates because both halves, (n + 1) / 2 and n / 2, are smaller than n + 1. The two subtree sizes differ by at most one. When n=2h−1n = 2^h - 1 the balanced tree is the perfect tree Tango.perfect with hh levels, as one can check by unfolding the definitions (no theorem states it); Tango uses both as reference trees (Section 26.1).

Theorem (balanced trees). The balanced tree on nn keys has nn keys, and every key lies at depth at most ⌊log⁡2n⌋\lfloor\log_2 n\rfloor. For n≥1n \ge 1 its height, in nodes, is exactly ⌊log⁡2n⌋+1\lfloor\log_2 n\rfloor + 1.

theoremClassical.Static.Results.balanced_sizepropext · Quot.soundClassical/Static/Abstract.lean:16
/-- The balanced tree has `n` keys (`Tree.balanced_size`). -/theorem balanced_size (n : Nat) : (balanced n).size = n :=  Tree.balanced_size n
theoremClassical.Static.Results.balanced_depthpropext · Classical.choice · Quot.soundClassical/Static/Abstract.lean:20
/-- Every key of the balanced tree lies at depth at most `⌊log₂ n⌋`. -/theorem balanced_depth (n x : Nat) (hx : x < n) : (balanced n).depth x ≤ Nat.log2 n :=  Static.balanced_depth n x hx
theoremClassical.Static.Results.balanced_height_eqpropext · Classical.choice · Quot.soundClassical/Static/Abstract.lean:45
/-- The balanced tree has height `⌊log₂ n⌋ + 1`… -/theorem balanced_height_eq (n : Nat) (h : 0 < n) : height (balanced n) = Nat.log2 n + 1 :=  Static.balanced_height_eq n h

No tree does better. A tree whose height is hh nodes holds at most 2h−12^h - 1 keys, so:

Theorem (minimum height). Every tree on n≥1n \ge 1 keys has height at least ⌊log⁡2n⌋+1\lfloor\log_2 n\rfloor + 1, and a key at depth at least ⌊log⁡2n⌋\lfloor\log_2 n\rfloor.

theoremClassical.Static.Results.log2_add_one_le_heightpropext · Classical.choice · Quot.soundClassical/Static/Abstract.lean:49
/-- …the minimum: every nonempty tree has height at least `⌊log₂ n⌋ + 1`. -/theorem log2_add_one_le_height (t : Tree) (h : 0 < t.size) : Nat.log2 t.size + 1 ≤ height t :=  Static.log2_add_one_le_height t h
theoremClassical.Static.Results.exists_deeppropext · Classical.choice · Quot.soundClassical/Static/Abstract.lean:24
/-- Conversely, every nonempty tree has a key at depth at least `⌊log₂ n⌋`. -/theorem exists_deep (t : Tree) (h : 0 < t.size) :    ∃ x < t.size, Nat.log2 t.size ≤ t.depth x :=  Static.exists_deep t h

Searching costs one plus the depth, which gives the two halves of the headline result, and the comparison with the logarithmic baseline Bounds.logCost of Chapter 14:

Theorem (the baseline). Searching the balanced tree costs at most m(1+⌊log⁡2n⌋)m(1 + \lfloor\log_2 n\rfloor), hence at most m(1+log⁡2n)m(1 + \log_2 n). Every nonempty tree has a key whose mm-fold repetition costs at least m(1+⌊log⁡2n⌋)m(1 + \lfloor\log_2 n\rfloor).

theoremClassical.Static.Results.balanced_costpropext · Classical.choice · Quot.soundClassical/Static/Abstract.lean:29
/-- Searching the balanced tree costs at most `1 + ⌊log₂ n⌋` per request. -/theorem balanced_cost (n : Nat) (xs : List Nat) (valid : ∀ x ∈ xs, x < n) :    StaticTree.cost (balanced n) xs ≤ xs.length * (Nat.log2 n + 1) :=  Static.balanced_cost n xs valid
theoremClassical.Static.Results.balanced_cost_le_logCostpropext · Classical.choice · Quot.soundClassical/Static/Abstract.lean:34
/-- The same bound against the real-valued baseline. -/theorem balanced_cost_le_logCost (n : Nat) (xs : List Nat) (valid : ∀ x ∈ xs, x < n) :    (StaticTree.cost (balanced n) xs : ℝ) ≤ Bounds.logCost n xs :=  Static.balanced_cost_le_logCost n xs valid
theoremClassical.Static.Results.exists_expensivepropext · Classical.choice · Quot.soundClassical/Static/Abstract.lean:39
/-- No static tree does better in the worst case: repeating a deepest key `m`times costs at least `m(1 + ⌊log₂ n⌋)`. -/theorem exists_expensive (t : Tree) (h : 0 < t.size) (m : Nat) :    ∃ x < t.size, m * (Nat.log2 t.size + 1) ≤ StaticTree.cost t (List.replicate m x) :=  Static.exists_expensive t h m

19.2 Entropy trees

Suppose that key xx is requested qxq_x times among mm requests. A tree in which xx has depth about log⁡2(m/qx)\log_2(m / q_x) serves the requests at cost about the entropy bound Bounds.staticCost. Both directions are formalized (Chapter 14):

The tree of the upper bound is built by a rule close to that of Mehlhorn (1975): put the weighted median at the root and recurse on both sides. This is the weighted search tree of Chapter 34, where every key of weight wxw_x lands at depth at most log⁡2(W/wx)\log_2(W/w_x). With weights on the keys only, the library’s bound is already the entropy plus one unit per request, with no constant factor. Mehlhorn’s analyses (Mehlhorn 1975; Mehlhorn 1977) also allow weights on the gaps between keys, for unsuccessful searches; they are not formalized.

19.3 Optimal static trees

The entropy tree is within a constant factor of the best static tree. The best static tree itself can be computed exactly, by dynamic programming over intervals of keys. The library writes intervals half-open: [i,j)[i, j) holds the keys i≤x<ji \le x < j. Let W(i,j)W(i, j) be the weight of the interval. A tree on [i,j)[i, j) puts some key rr at its root, and every search in the interval passes through the root. So the cheapest tree uses the cheapest trees on both sides:

C(i,j)  =  W(i,j)+min⁡i≤r<j(C(i,r)+C(r+1,j)),C(i,i)=0.C(i, j) \;=\; W(i, j) + \min_{i \le r < j} \bigl( C(i, r) + C(r + 1, j) \bigr), \qquad C(i, i) = 0 .

Computed directly this takes O(n3)O(n^3) time; Gilbert and Moore (1959) used the same recurrence when only the gaps carry weight. Knuth (1971) observed that the optimal roots are monotone: some optimal root of [i,j)[i, j) lies between optimal roots of [i,j−1)[i, j - 1) and of [i+1,j)[i + 1, j). Restricting the minimum to that window makes the total work O(n2)O(n^2). Yao (1980) explained why: whenever the weight satisfies the quadrangle inequality and is monotone on nested intervals, the cost CC satisfies the quadrangle inequality too, and that makes the optimal roots monotone.

The library follows Yao. Everything is stated for an abstract interval weight W, and key weights are one instance. Weights on the gaps between keys, for unsuccessful searches, would be another additive instance; it is not stated separately, because in the models of this book every request is a key.

19.3.1 The recurrence

defClassical.Static.Optimal.costpropext · Quot.soundClassical/Static/Optimal/Definitions/Abstract.lean:19
/-- The cubic recurrence `C(i, j) = W(i, j) + min_{i ≤ r < j} (C(i, r) + C(r + 1, j))`,with `C(i, j) = 0` for an empty interval. -/def cost (W : Nat → Nat → Nat) (i j : Nat) : Nat :=  if i < j then    W i j + ((List.finRange (j - i)).map fun r : Fin (j - i) =>      cost W i (i + r) + cost W (i + r + 1) j).foldr min (cost W i i + cost W (i + 1) j)  else 0termination_by j - idecreasing_by all_goals omega
defClassical.Static.Optimal.candidatepropext · Quot.soundClassical/Static/Optimal/Definitions/Abstract.lean:29
/-- The cost of the interval `[i, j)` with root `r`. -/def candidate (W : Nat → Nat → Nat) (i j r : Nat) : Nat :=  W i j + cost W i r + cost W (r + 1) j
defClassical.Static.Optimal.rootpropext · Quot.soundClassical/Static/Optimal/Definitions/Abstract.lean:33
/-- The largest optimal root of `[i, j)` (Knuth's `R(i, j)`); `i` when theinterval is empty. -/def root (W : Nat → Nat → Nat) (i j : Nat) : Nat :=  i + Nat.findGreatest (fun d => candidate W i j (i + d) = cost W i j) (j - i - 1)
defClassical.Static.Optimal.treepropext · Classical.choice · Quot.soundClassical/Static/Optimal/Definitions/Abstract.lean:38
/-- The tree built from the largest optimal roots. -/def tree (W : Nat → Nat → Nat) (i j : Nat) : Tree :=  if i < j then .node (tree W i (root W i j)) (tree W (root W i j + 1) j) else .niltermination_by j - idecreasing_by  all_goals    have := Nat.findGreatest_le (P := fun d => candidate W i j (i + d) = cost W i j) (j - i - 1)    simp only [root]    omega

cost W i j is the recurrence, with the minimum written as a fold over the roots i + r for r < j - i. root W i j is Knuth’s R(i,j)R(i, j), the largest optimal root, found by Nat.findGreatest; any consistent choice would do, and the largest one makes the monotonicity statements below hold as written. tree W i j builds the tree from these roots.

The cost of an arbitrary tree is the weight of the interval of every subtree, summed over all subtrees. This is LazyFinger.intervalCost of Chapter 15, the same sum that the optimal lazy-finger tree uses. With key weights it is the weighted depth ∑xwx(depth(x)+1)\sum_x w_x(\mathrm{depth}(x) + 1), as shown below.

Theorem (the recurrence is optimal). tree W i j has the j−ij - i keys of the interval, its cost is cost W i j, and no tree on those keys costs less.

theoremClassical.Static.Optimal.Results.tree_sizepropext · Classical.choice · Quot.soundClassical/Static/Optimal/Abstract.lean:16
/-- The recurrence builds a tree on the keys of `[i, j)`… -/theorem tree_size (W : Nat → Nat → Nat) (i j : Nat) : (tree W i j).size = j - i :=  Optimal.tree_size W i j
theoremClassical.Static.Optimal.Results.tree_costpropext · Classical.choice · Quot.soundClassical/Static/Optimal/Abstract.lean:20
/-- …whose cost is the value of the recurrence… -/theorem tree_cost (W : Nat → Nat → Nat) (i j : Nat) : LazyFinger.intervalCost W (tree W i j) i = cost W i j :=  Optimal.tree_cost W i j
theoremClassical.Static.Optimal.Results.cost_le_intervalCostpropext · Quot.soundClassical/Static/Optimal/Abstract.lean:24
/-- …and no tree on those keys costs less. -/theorem cost_le_intervalCost (W : Nat → Nat → Nat) (t : Tree) (i j : Nat) (h : t.size = j - i) :    cost W i j ≤ LazyFinger.intervalCost W t i :=  Optimal.cost_le_intervalCost W t i j h

19.3.2 Yao’s quadrangle inequality

defClassical.Static.Optimal.Quadrangleno axiomsClassical/Static/Optimal/Definitions/Abstract.lean:48
/-- The quadrangle inequality `W(i, j) + W(i', j') ≤ W(i', j) + W(i, j')` for`i ≤ i' ≤ j ≤ j'`. -/def Quadrangle (W : Nat → Nat → Nat) : Prop :=  ∀ i i' j j', i ≤ i' → i' ≤ j → j ≤ j' → W i j + W i' j' ≤ W i' j + W i j'
defClassical.Static.Optimal.InclusionMonotoneno axiomsClassical/Static/Optimal/Definitions/Abstract.lean:53
/-- Monotonicity under inclusion: `W(i', j) ≤ W(i, j')` when `[i', j) ⊆ [i, j')`. -/def InclusionMonotone (W : Nat → Nat → Nat) : Prop :=  ∀ i i' j j', i ≤ i' → i' ≤ j → j ≤ j' → W i' j ≤ W i j'

Theorem (Yao; Knuth’s inequalities). If the weight satisfies the quadrangle inequality and is monotone under inclusion, then the optimal cost satisfies the quadrangle inequality too, and the largest optimal roots are monotone: R(i,j)≤R(i,j+1)R(i, j) \le R(i, j + 1) and R(i,j)≤R(i+1,j)R(i, j) \le R(i + 1, j).

theoremClassical.Static.Optimal.Results.cost_quadranglepropext · Classical.choice · Quot.soundClassical/Static/Optimal/Abstract.lean:29
/-- **Yao.** The optimal cost inherits the quadrangle inequality from amonotone interval weight. -/theorem cost_quadrangle (W : Nat → Nat → Nat) (hQ : Quadrangle W) (hM : InclusionMonotone W) :    Quadrangle (cost W) :=  Optimal.cost_quadrangle hQ hM
theoremClassical.Static.Optimal.Results.root_le_root_rightpropext · Classical.choice · Quot.soundClassical/Static/Optimal/Abstract.lean:35
/-- **Knuth's inequalities**, first half: `R(i, j) ≤ R(i, j + 1)`. -/theorem root_le_root_right (W : Nat → Nat → Nat) (hQ : Quadrangle W) (hM : InclusionMonotone W)    {i j : Nat} (h : i < j) : root W i j ≤ root W i (j + 1) :=  Optimal.root_le_root_right hQ hM h
theoremClassical.Static.Optimal.Results.root_le_root_leftpropext · Classical.choice · Quot.soundClassical/Static/Optimal/Abstract.lean:40
/-- **Knuth's inequalities**, second half: `R(i, j) ≤ R(i + 1, j)`. -/theorem root_le_root_left (W : Nat → Nat → Nat) (hQ : Quadrangle W) (hM : InclusionMonotone W)    {i j : Nat} (h : i + 1 < j) : root W i j ≤ root W (i + 1) j :=  Optimal.root_le_root_left hQ hM h

19.3.3 Knuth’s algorithm

Knuth’s algorithm fills the table of costs and roots by increasing interval length. For an interval of length at least two it examines only the roots between R(i,j−1)R(i, j - 1) and R(i+1,j)R(i + 1, j). Along each diagonal of the table these windows overlap only at their ends, so a whole diagonal examines O(n)O(n) roots, and the whole table O(n2)O(n^2).

defClassical.Static.Optimal.scanno axiomsClassical/Static/Optimal/Definitions/Abstract.lean:57
/-- Among the roots `lo ≤ r ≤ hi`, the least candidate cost and the largestroot attaining it. Each root examined is one step. -/def scan (W : Nat → Nat → Nat) (C : Nat → Nat → Nat) (i j lo hi : Nat) : Nat × Nat :=  (List.range' (lo + 1) (hi - lo)).foldl    (fun best r => if W i j + C i r + C (r + 1) j ≤ best.1 then (W i j + C i r + C (r + 1) j, r) else best)    (W i j + C i lo + C (lo + 1) j, lo)
defClassical.Static.Optimal.knuthEntryno axiomsClassical/Static/Optimal/Definitions/Abstract.lean:64
/-- One table entry of Knuth's algorithm, from tables `C`, `K` filled for allshorter intervals: (cost, root, steps). A single key is its own root; a longerinterval searches only between the roots of its two maximal subintervals. -/def knuthEntry (W : Nat → Nat → Nat) (C K : Nat → Nat → Nat) (i j : Nat) : Nat × Nat × Nat :=  if j = i + 1 then (W i j, i, 1)  else    let lo := K i (j - 1)    let hi := K (i + 1) j    let best := scan W C i j lo hi    (best.1, best.2, hi + 1 - lo)
defClassical.Static.Optimal.knuthTablespropextClassical/Static/Optimal/Definitions/Abstract.lean:75
/-- Knuth's tables for all intervals of `[0, n)` of length at most `len`, byincreasing length, with the total number of steps. -/def knuthTables (W : Nat → Nat → Nat) (n : Nat) :    Nat → (Nat → Nat → Nat) × (Nat → Nat → Nat) × Nat  | 0 => (fun _ _ => 0, fun i _ => i, 0)  | len + 1 =>      let prev := knuthTables W n len      let entry := fun i => knuthEntry W prev.1 prev.2.1 i (i + len + 1)      (fun i j => if j = i + len + 1 then (entry i).1 else prev.1 i j,       fun i j => if j = i + len + 1 then (entry i).2.1 else prev.2.1 i j,       prev.2.2 + ((List.range (n - len)).map fun i => (entry i).2.2).sum)
defClassical.Static.Optimal.knuthpropextClassical/Static/Optimal/Definitions/Abstract.lean:87
/-- Knuth's `O(n²)` algorithm on `[0, n)`: (optimal cost, steps). -/def knuth (W : Nat → Nat → Nat) (n : Nat) : Nat × Nat :=  let t := knuthTables W n n  (t.1 0 n, t.2.2)

Theorem (Knuth). Under the same two hypotheses, Knuth’s algorithm returns the optimal cost of [0,n)[0, n) and examines at most 2n22n^2 candidate roots.

theoremClassical.Static.Optimal.Results.knuth_costpropext · Classical.choice · Quot.soundClassical/Static/Optimal/Abstract.lean:45
/-- Knuth's algorithm computes the recurrence… -/theorem knuth_cost (W : Nat → Nat → Nat) (hQ : Quadrangle W) (hM : InclusionMonotone W) (n : Nat) :    (knuth W n).1 = cost W 0 n :=  Optimal.knuth_cost hQ hM n
theoremClassical.Static.Optimal.Results.knuth_stepspropext · Classical.choice · Quot.soundClassical/Static/Optimal/Abstract.lean:50
/-- …examining at most `2n²` candidate roots. -/theorem knuth_steps (W : Nat → Nat → Nat) (hQ : Quadrangle W) (hM : InclusionMonotone W) (n : Nat) :    (knuth W n).2 ≤ 2 * n ^ 2 :=  Optimal.knuth_steps hQ hM n
What the step count measures

knuth returns a count of the candidate roots it examines, not a running time in a machine model. Each examination is a constant number of table lookups and additions, so the count is the usual measure of the algorithm’s work. The tables are functions in Lean, not arrays, so the Lean evaluation itself is not quadratic.

19.3.4 Key weights and request sequences

For key weights w0,…,wn−1w_0, \dots, w_{n-1}, the interval weight is the sum of the weights in the interval:

defClassical.Static.weightedCostpropext · Classical.choice · Quot.soundClassical/Static/Optimal/Definitions/Abstract.lean:97
/-- The weighted search cost of a tree: `∑ₓ w[x] · (depth x + 1)`. -/def weightedCost (w : List Nat) (t : Tree) : Nat :=  ∑ x ∈ Finset.range t.size, w.getD x 0 * (t.depth x + 1)
defClassical.Static.rangeWeightpropext · Classical.choice · Quot.soundClassical/Static/Optimal/Definitions/Abstract.lean:101
/-- The total key weight of the interval `[i, j)`. -/def rangeWeight (w : List Nat) (i j : Nat) : Nat :=  ∑ x ∈ Finset.Ico i j, w.getD x 0
defClassical.Static.optCostpropext · Classical.choice · Quot.soundClassical/Static/Optimal/Definitions/Abstract.lean:105
/-- The optimal weighted cost over trees on the `w.length` keys, by the recurrence. -/def optCost (w : List Nat) : Nat := Optimal.cost (rangeWeight w) 0 w.length
defClassical.Static.optTreepropext · Classical.choice · Quot.soundClassical/Static/Optimal/Definitions/Abstract.lean:108
/-- An optimal tree, built from the largest optimal roots. -/def optTree (w : List Nat) : Tree := Optimal.tree (rangeWeight w) 0 w.length
defClassical.Static.countsno axiomsClassical/Static/Optimal/Definitions/Abstract.lean:111
/-- Request counts of the keys `0, …, n - 1`. -/def counts (n : Nat) (xs : List Nat) : List Nat := (List.range n).map xs.count

Theorem (key weights). Interval sums satisfy the quadrangle inequality (in fact with equality) and are monotone under inclusion. The interval cost of a tree is its weighted depth. The optimal tree has nn keys and costs optCost w, no tree costs less, and Knuth’s algorithm computes this cost with at most 2n22n^2 steps.

theoremClassical.Static.Optimal.Results.rangeWeight_quadranglepropext · Classical.choice · Quot.soundClassical/Static/Optimal/Abstract.lean:57
theorem rangeWeight_quadrangle (w : List Nat) : Quadrangle (rangeWeight w) :=  Static.rangeWeight_quadrangle w
theoremClassical.Static.Optimal.Results.rangeWeight_monotonepropext · Classical.choice · Quot.soundClassical/Static/Optimal/Abstract.lean:60
theorem rangeWeight_monotone (w : List Nat) : InclusionMonotone (rangeWeight w) :=  Static.rangeWeight_monotone w
theoremClassical.Static.Optimal.Results.weightedCost_eq_intervalCostpropext · Classical.choice · Quot.soundClassical/Static/Optimal/Abstract.lean:63
/-- The subtree-weight cost is the weighted depth cost. -/theorem weightedCost_eq_intervalCost (w : List Nat) (t : Tree) :    weightedCost w t = LazyFinger.intervalCost (rangeWeight w) t 0 :=  Static.weightedCost_eq_intervalCost w t
theoremClassical.Static.Optimal.Results.optTree_sizepropext · Classical.choice · Quot.soundClassical/Static/Optimal/Abstract.lean:68
theorem optTree_size (w : List Nat) : (optTree w).size = w.length :=  Static.optTree_size w
theoremClassical.Static.Optimal.Results.optTree_costpropext · Classical.choice · Quot.soundClassical/Static/Optimal/Abstract.lean:71
theorem optTree_cost (w : List Nat) : weightedCost w (optTree w) = optCost w :=  Static.optTree_cost w
theoremClassical.Static.Optimal.Results.optCost_lepropext · Classical.choice · Quot.soundClassical/Static/Optimal/Abstract.lean:74
theorem optCost_le (w : List Nat) (t : Tree) (h : t.size = w.length) :    optCost w ≤ weightedCost w t :=  Static.optCost_le w t h
theoremClassical.Static.Optimal.Results.knuth_optCostpropext · Classical.choice · Quot.soundClassical/Static/Optimal/Abstract.lean:78
theorem knuth_optCost (w : List Nat) : (knuth (rangeWeight w) w.length).1 = optCost w :=  Static.knuth_optCost w
theoremClassical.Static.Optimal.Results.knuth_steps_lepropext · Classical.choice · Quot.soundClassical/Static/Optimal/Abstract.lean:81
theorem knuth_steps_le (w : List Nat) : (knuth (rangeWeight w) w.length).2 ≤ 2 * w.length ^ 2 :=  Static.knuth_steps_le w

With the request counts of a sequence as weights, the weighted cost is the static search cost. So optCost (counts n xs) is RF∗\mathrm{RF}^*, the cost of the best static tree in the map of the bounds, and it lies between a third of the entropy bound and the entropy bound:

Theorem (the best static tree for a sequence). Searching a tree costs its weighted cost under the request counts. The optimal tree for the counts serves the sequence at cost optCost, and every tree on the same keys costs at least that much. This optimum is between a third of the entropy bound and the entropy bound, and at most m(1+⌊log⁡2n⌋)m(1 + \lfloor\log_2 n\rfloor).

theoremClassical.Static.Optimal.Results.staticCost_eq_weightedCostpropext · Classical.choice · Quot.soundClassical/Static/Optimal/Abstract.lean:86
/-- Searching a fixed tree from the root costs its weighted cost under therequest counts. -/theorem staticCost_eq_weightedCost (t : Tree) (xs : List Nat) (valid : ∀ x ∈ xs, x < t.size) :    StaticTree.cost t xs = weightedCost (counts t.size xs) t :=  Static.staticCost_eq_weightedCost t xs valid
theoremClassical.Static.Optimal.Results.optTree_staticpropext · Classical.choice · Quot.soundClassical/Static/Optimal/Abstract.lean:92
theorem optTree_static (n : Nat) (xs : List Nat) (valid : ∀ x ∈ xs, x < n) :    (optTree (counts n xs)).size = n ∧      StaticTree.cost (optTree (counts n xs)) xs = optCost (counts n xs) :=  ⟨Static.optTree_counts_size n xs, Static.optTree_static n xs valid⟩
theoremClassical.Static.Optimal.Results.optCost_le_staticpropext · Classical.choice · Quot.soundClassical/Static/Optimal/Abstract.lean:97
theorem optCost_le_static (n : Nat) (xs : List Nat) (t : Tree) (ht : t.size = n)    (valid : ∀ x ∈ xs, x < n) : optCost (counts n xs) ≤ StaticTree.cost t xs :=  Static.optCost_le_static n xs t ht valid
theoremClassical.Static.Optimal.Results.optCost_entropypropext · Classical.choice · Quot.soundClassical/Static/Optimal/Abstract.lean:101
/-- The best static tree lies between a third of the entropy bound and theentropy bound itself. -/theorem optCost_entropy (n : Nat) (xs : List Nat) (valid : ∀ x ∈ xs, x < n) :    Bounds.staticCost n xs ≤ 3 * (optCost (counts n xs) : ℝ) ∧      (optCost (counts n xs) : ℝ) ≤ Bounds.staticCost n xs :=  ⟨Static.entropy_le_optCost n xs valid, Static.optCost_le_entropy n xs valid⟩
theoremClassical.Static.Optimal.Results.optCost_le_balancedpropext · Classical.choice · Quot.soundClassical/Static/Optimal/Abstract.lean:108
theorem optCost_le_balanced (n : Nat) (xs : List Nat) (valid : ∀ x ∈ xs, x < n) :    optCost (counts n xs) ≤ xs.length * (Nat.log2 n + 1) :=  Static.optCost_le_balanced n xs valid

The Isabelle Archive of Formal Proofs has a formalization of the same three steps, the recurrence, Yao’s inequality and Knuth’s algorithm (Nipkow and Somogyi 2018).

19.4 Further results

When only the gaps carry weight, the searches all end at leaves, and the problem becomes that of optimal alphabetic codes. The algorithms of Hu and Tucker (1971) and Garsia and Wachs (1977) solve it in O(nlog⁡n)O(n \log n) time. They are listed as a stretch goal in the roadmap (S3).