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

Chapter 27The optimal lazy-finger tree

A static binary search tree with a lazy finger serves each request by walking, along tree edges, from the previously requested key to the new one; the first search starts at the root. Chapter 15 introduced this model and its cost, and characterized the optimal cost up to constant factors. That characterization is not an algorithm. This chapter gives one: Theorem 8 of Bose, Douïeb, Iacono and Langerman (2016) computes an optimal lazy-finger tree exactly, by a dynamic program over key intervals that runs in cubic time once the request sequence has been summarized.

The library proves two things about this algorithm. It returns a tree whose lazy-finger cost equals the optimum over all shapes. And, in an explicit, annotated cost model for a random-access machine, its work is at most 4m+64(n+1)34m + 64(n+1)^3 for mm requests on nn keys.

Key result · Bose et al. 2016
An optimal lazy-finger tree can be computed with 4m+64(n+1)34m + 64(n+1)^3 work

Let X=x1,…,xmX = x_1, \dots, x_m be a sequence of keys from {0,…,n−1}\{0, \dots, n-1\}. A static BST TT on these keys serves XX with a lazy finger at cost

costT(X)  =  ∑j=1m(1+dT(xj−1,xj)),\mathrm{cost}_T(X) \;=\; \sum_{j=1}^{m} \bigl(1 + d_T(x_{j-1}, x_j)\bigr),

where dT(x,y)d_T(x, y) is the number of edges on the path between xx and yy in TT, and x0x_0 is the root of TT: one unit per request, plus the edges the finger walks. There is an explicit algorithm that, given nn and XX, returns a tree T∗T^\ast with nn nodes such that

costT∗(X)  =  min⁡T with n nodescostT(X),\mathrm{cost}_{T^\ast}(X) \;=\; \min_{T \text{ with } n \text{ nodes}} \mathrm{cost}_T(X),

and whose work, counted in an explicit unit-cost RAM model, is at most 4m+64(n+1)34m + 64(n+1)^3. The bound holds for every nn, including n=0n = 0, with no hidden constants. The same holds when the first search starts from a specified key p<np < n instead of the root, that is, with x0=px_0 = p.

In Lean, the algorithms are Work.tree n xs and Work.treeFrom n p xs, computations in the cost model Work.Computation: .ret is the returned tree and .time the counted work. The costs are LazyFinger.cost and LazyFinger.costFrom, and the optima LazyFinger.optimalCost and LazyFinger.optimalCostFrom, defined as infima over all shapes with nn nodes; the theorems show that the returned tree attains them. The work is the sum of the charges declared in the model’s program text, not a measurement of Lean’s own running time.

The Lean statements
theoremOptimalLazyFinger.Work.Results.root_startpropext · Classical.choice · Quot.soundAlgorithms/OptimalLazyFinger/Work/Abstract.lean:18
/-- Exact optimality and an end-to-end cubic work bound, in the cost model of`Work.Model.Abstract`. This includes root initialization and empty instances. -/theorem root_start (n : Nat) (xs : List Nat) (valid : ∀ x ∈ xs, x < n) :    (tree n xs).ret.size = n ∧      LazyFinger.cost (tree n xs).ret xs = LazyFinger.optimalCost n xs ∧      (tree n xs).time ≤ 4 * xs.length + 64 * (n + 1) ^ 3 := … tree_spec n xs valid
theoremOptimalLazyFinger.Work.Results.specified_startpropext · Classical.choice · Quot.soundAlgorithms/OptimalLazyFinger/Work/Abstract.lean:25
/-- The same guarantee with a specified initial key. -/theorem specified_start (n p : Nat) (xs : List Nat)    (hp : p < n) (valid : ∀ x ∈ xs, x < n) :    (treeFrom n p xs).ret.size = n ∧      LazyFinger.costFrom (treeFrom n p xs).ret p xs = LazyFinger.optimalCostFrom n p xs ∧      (treeFrom n p xs).time ≤ 4 * xs.length + 64 * (n + 1) ^ 3 := … treeFrom_spec n p xs hp valid
36 definitions in 4 chapters · reading list

To confirm the result, the box is enough, but its reading path is longer than usual: besides the lazy-finger cost of Chapter 15, it contains the whole annotated program, because a work bound is only as meaningful as the charges it adds up. Section 27.7 and Section 27.8 explain what is charged and why. The rest of the chapter explains why the algorithm is correct. Section 27.1 gives the plan. Section 27.2 rewrites the lazy-finger cost as a sum over subtrees, Section 27.3 and Section 27.4 solve the resulting interval problem, Section 27.5 computes its inputs from the sequence, and Section 27.6 assembles the optimizer and proves it exact. Section 27.9 states the work theorems.

The definitions are in Algorithms/OptimalLazyFinger/Definitions/Abstract.lean, Preprocessing/Definitions/Abstract.lean, Work/Model/Abstract.lean and Work/Definitions/Abstract.lean; the theorems are in Algorithms/OptimalLazyFinger/Abstract.lean and Work/Abstract.lean.

27.1 The plan

The optimal root-finger tree, where every search starts at the root, has a classical dynamic program: the cost of a tree is a sum, over its subtrees, of a quantity that depends only on the subtree’s key interval, so the best tree on an interval is obtained by trying every root and combining the best trees on the two sides. The lazy-finger cost has the same structure, once it is written the right way.

  1. Edges as boundary crossings. The edge from a subtree to its parent is walked exactly when the finger moves from a key inside the subtree to a key outside it, or back. So the walking part of the lazy-finger cost is the sum, over all subtrees, of the number of consecutive request pairs that cross the subtree’s boundary. That number, the boundary toll of the subtree’s key interval, depends on the interval only, not on the shape.
  2. Interval dynamic programming. For any toll w(lo,hi)w(lo, hi) on half-open intervals, the shape minimizing ∑subtreesw(interval)\sum_{\text{subtrees}} w(\text{interval}) satisfies Bellman’s recurrence over intervals. A table indexed by interval length and start computes it with O(n)O(n) choices for each of O(n2)O(n^2) intervals: O(n3)O(n^3).
  3. Tolls in constant time. The toll of [lo,hi)[lo, hi) is a sum of the transition counts F[a][b]F[a][b], the number of times the request sequence moves from key aa to key bb, over four rectangles of the matrix FF. After one pass over the sequence to fill FF, in O(m)O(m), and two-dimensional prefix sums, in O(n2)O(n^2), each toll costs four rectangle queries.
  4. Root start. A virtual extra key nn, outside every subtree, plays the previous request of x1x_1. It makes the first search cost one edge more than a walk from the root, whatever the shape, so it does not change which tree is optimal.

The library proves each step exactly, then annotates the same program with explicit operation counts and bounds their sum.

27.2 Boundary tolls

The edge decomposition is part of Chapter 15. It uses the two definitions LazyFinger.cut, which is 11 when exactly one of two keys lies in a half-open interval [lo,hi)[lo, hi), and LazyFinger.crossings, which sums cut lo hi over the consecutive pairs (xj−1,xj)(x_{j-1}, x_j) of a sequence with an explicit initial key x0x_0. The cost of a shape is then LazyFinger.intervalCost w t lo: the sum of w(lo′,hi′)w(lo', hi') over the key intervals [lo′,hi′)[lo', hi') of all nonempty subtrees of t, including t itself, when t’s keys are numbered from lo.

Two theorems of that chapter connect this to the lazy-finger cost. For a specified start pp inside the tree, Results.sequence says

costFromT(p,X)  =  m+intervalCost(crossings(⋅,⋅,p,X), T).\mathrm{costFrom}_T(p, X) \;=\; m + \mathrm{intervalCost}\bigl(\mathrm{crossings}(\cdot, \cdot, p, X),\, T\bigr).

The whole tree’s interval contains every key, so its toll is 00 and only proper subtrees, that is edges, contribute. For the root start, Results.initialization takes the virtual initial key n=∣T∣n = |T|, which lies outside every subtree. The first transition n→x1n \to x_1 then crosses the boundary of every subtree that contains x1x_1, which is depth(x1)+1\mathrm{depth}(x_1) + 1 subtrees, while the root-start search for x1x_1 walks depth(x1)\mathrm{depth}(x_1) edges. So

costT(X)+[X≠ε]  =  m+intervalCost(crossings(⋅,⋅,n,X), T),\mathrm{cost}_T(X) + [X \neq \varepsilon] \;=\; m + \mathrm{intervalCost}\bigl(\mathrm{crossings}(\cdot, \cdot, n, X),\, T\bigr),

where [X≠ε][X \ne \varepsilon] is 11 for a nonempty sequence. In both cases, the lazy-finger cost and the interval cost differ by a quantity that does not depend on TT. A shape minimizing one minimizes the other.

27.3 Bellman’s recurrence

The interval problem is: given a toll w:N×N→Nw : \mathbb{N} \times \mathbb{N} \to \mathbb{N}, find a shape with nn nodes minimizing intervalCost w t 0. The definition of LazyFinger.intervalCost splits at the root: a tree node l r on keys starting at lo pays w(lo,lo+∣l∣+∣r∣+1)w(lo, lo + |l| + |r| + 1) for its own interval, plus the interval cost of l on keys from lo and of r on keys from lo + |l| + 1. The two subproblems are independent, so, writing OPT(k,lo)\mathrm{OPT}(k, lo) for the optimum on the kk keys lo,…,lo+k−1lo, \dots, lo + k - 1,

OPT(0,lo)=0,OPT(k+1,lo)  =  w(lo, lo+k+1)+min⁡0≤r≤k(OPT(r,lo)+OPT(k−r, lo+r+1)),\mathrm{OPT}(0, lo) = 0, \qquad \mathrm{OPT}(k + 1, lo) \;=\; w(lo,\, lo + k + 1) + \min_{0 \le r \le k} \bigl(\mathrm{OPT}(r, lo) + \mathrm{OPT}(k - r,\, lo + r + 1)\bigr),

where rr is the number of keys in the left subtree, so the root is key lo+rlo + r.

defOptimalLazyFinger.Entryno axiomsAlgorithms/OptimalLazyFinger/Definitions/Abstract.lean:10
/-- A constructed shape paired with its boundary-toll cost. -/abbrev Entry := Tree × Nat
defOptimalLazyFinger.chooseno axiomsAlgorithms/OptimalLazyFinger/Definitions/Abstract.lean:13
/-- Keep the cheaper candidate, breaking ties in favor of the first. -/def choose (a b : Entry) : Entry := if a.2 ≤ b.2 then a else b
defOptimalLazyFinger.minimumno axiomsAlgorithms/OptimalLazyFinger/Definitions/Abstract.lean:16
/-- Fold a finite family of candidates with a supplied initial candidate. -/def minimum (initial : Entry) (candidates : List Entry) : Entry :=  candidates.foldr choose initial

An Entry is a candidate solution: a shape together with its cost. choose keeps the cheaper of two entries and, on a tie, the first; minimum initial candidates folds choose from the right over the list, ending with initial. A fold needs a starting value, which is why minimum takes one; the optimizer passes the first candidate, which is also in the list, so it changes nothing. With this fold and tie rule, the earliest minimizing candidate in the list wins.

defOptimalLazyFinger.solvepropext · Quot.soundAlgorithms/OptimalLazyFinger/Definitions/Abstract.lean:20
/-- Bellman's interval recurrence with reconstruction of a minimizing shape.This direct evaluator recomputes shared subproblems; tabulation is needed forthe paper's cubic running time. `n` is the interval length, `lo` its first key. -/def solve (w : Nat → Nat → Nat) : (n lo : Nat) → Entry  | 0, _ => (.nil, 0)  | n + 1, lo =>      let candidate (k : Fin (n + 1)) : Entry :=        let l := solve w k.val lo        let r := solve w (n - k.val) (lo + k.val + 1)        (.node l.1 r.1, w lo (lo + n + 1) + l.2 + r.2)      minimum (candidate ⟨0, Nat.zero_lt_succ n⟩) ((List.finRange (n + 1)).map candidate)termination_by n => ndecreasing_by all_goals omega

solve w n lo is the recurrence verbatim, returning both the cost and a minimizing shape. Its arguments are the interval length n and the first key lo. Each candidate k builds the node whose left subtree is the solution on the first k keys and whose right subtree is the solution on the remaining n - k, and its cost is the toll of the whole interval plus the two sub-costs. The candidates are listed by increasing k, so ties go to the smallest left subtree. As its docstring says, solve is a specification: it recomputes shared subproblems and takes exponential time. Its role is to fix, once and for all, which optimal shape the efficient algorithm returns.

27.4 Filling the table

The efficient evaluation stores every subproblem in a table with one row per interval length.

defOptimalLazyFinger.lookupno axiomsAlgorithms/OptimalLazyFinger/Definitions/Abstract.lean:34
/-- Total table lookup; correctness uses only entries within the built rows. -/def lookup (table : Array (Array Entry)) (n lo : Nat) : Entry :=  (table[n]?.getD #[])[lo]?.getD (.nil, 0)
defOptimalLazyFinger.tabulatepropextAlgorithms/OptimalLazyFinger/Definitions/Abstract.lean:38
/-- One row for each interval length, evaluated from shorter intervals upward.The universe size fixes the row width. Invalid intervals are unused. -/def tabulate (w : Nat → Nat → Nat) (univSize : Nat) : Nat → Array (Array Entry)  | 0 => #[Array.replicate (univSize + 1) (.nil, 0)]  | n + 1 =>      let previous := tabulate w univSize n      previous.push (Array.ofFn fun lo : Fin (univSize + 1) =>        if lo.val + n + 1 ≤ univSize then          let candidate (k : Fin (n + 1)) : Entry :=            let l := lookup previous k.val lo.val            let r := lookup previous (n - k.val) (lo.val + k.val + 1)            (.node l.1 r.1, w lo.val (lo.val + n + 1) + l.2 + r.2)          minimum (candidate ⟨0, Nat.zero_lt_succ n⟩) ((List.finRange (n + 1)).map candidate)        else (.nil, 0))
defOptimalLazyFinger.optimizepropextAlgorithms/OptimalLazyFinger/Definitions/Abstract.lean:53
/-- Table-based interval optimization, returning the shape and its cost. -/def optimize (w : Nat → Nat → Nat) (n : Nat) : Entry :=  lookup (tabulate w n n) n 0

tabulate w univSize stages builds rows 0,1,…,stages0, 1, \dots, \mathit{stages}. Row nn has one entry for every start lo∈{0,…,univSize}lo \in \{0, \dots, \mathit{univSize}\}; the entry is the solution on the interval [lo,lo+n)[lo, lo + n) if that interval fits in the universe, and the placeholder (.nil, 0) otherwise. Row 00 is all empty trees. Row n+1n + 1 is computed from the rows already built, by the same candidates as in solve, with lookup in place of the recursive calls. lookup is a total read: it returns (.nil, 0) outside the table, a value that the theorems never use. optimize w n builds the table for a universe of nn keys and reads the entry for the whole interval [0,n)[0, n).

Theorem (cached recurrence). For every toll ww, every valid interval, of length nn at most the number of rows built and with lo+n≤univSizelo + n \le \mathit{univSize}, the table entry is exactly the recursive solution, including the shape chosen among ties.

theoremOptimalLazyFinger.Results.cached_recurrencepropext · Classical.choice · Quot.soundAlgorithms/OptimalLazyFinger/Abstract.lean:9
/-- The table stores exactly the recursively specified solution for each validinterval, including the minimizing shape and deterministic tie breaking. -/theorem cached_recurrence (w : Nat → Nat → Nat) (univSize stages n lo : Nat)    (hn : n ≤ stages) (valid : lo + n ≤ univSize) :    lookup (tabulate w univSize stages) n lo = solve w n lo :=  tabulate_lookup w univSize stages n lo hn valid

Theorem (the interval optimizer). For every toll ww and every nn, optimize w n returns a shape with nn nodes, its reported cost is the shape’s interval cost, and no shape with nn nodes has a smaller interval cost.

theoremOptimalLazyFinger.Results.boundary_optimalpropext · Classical.choice · Quot.soundAlgorithms/OptimalLazyFinger/Abstract.lean:16
/-- Optimizing arbitrary interval tolls returns a shape of the requested size,its exact cost, and a cost no greater than that of any competing shape. -/theorem boundary_optimal (w : Nat → Nat → Nat) (n : Nat) :    (optimize w n).1.size = n ∧      LazyFinger.intervalCost w (optimize w n).1 0 = (optimize w n).2 ∧      ∀ t : Tree, t.size = n → (optimize w n).2 ≤ LazyFinger.intervalCost w t 0 :=  optimize_spec w n

The toll is arbitrary here: any function of the interval endpoints. This is the general form of the classical optimal-BST recurrence. For instance, with w(lo,hi)w(lo, hi) the total access frequency of the keys in [lo,hi)[lo, hi), each key is charged once for every subtree that contains it, that is, its depth plus one, and the optimizer computes an optimal root-finger tree.

27.5 Counting transitions

The lazy-finger toll of an interval is the number of consecutive request pairs that cross its boundary. Computing it naively from the sequence costs O(m)O(m) for each of the O(n2)O(n^2) intervals. Instead, the optimizer summarizes the sequence once, in the n×nn \times n matrix of directed transition counts F[a][b]=#{j:xj−1=a, xj=b}F[a][b] = \#\{j : x_{j-1} = a,\ x_j = b\}, with the initial key as x0x_0. A pair crosses the boundary of [lo,hi)[lo, hi) exactly when one endpoint is inside and the other is outside, to the left or to the right, so

w(lo,hi)  =  F([lo,hi)×[0,lo))+F([lo,hi)×[hi,n))+F([0,lo)×[lo,hi))+F([hi,n)×[lo,hi)),w(lo, hi) \;=\; F\bigl([lo,hi) \times [0,lo)\bigr) + F\bigl([lo,hi) \times [hi,n)\bigr) + F\bigl([0,lo) \times [lo,hi)\bigr) + F\bigl([hi,n) \times [lo,hi)\bigr),

where F(A×B)F(A \times B) is the sum of the entries with row in AA and column in BB. These are the moves from inside to the left, from inside to the right, from the left to inside, and from the right to inside. With two-dimensional prefix sums of FF, each rectangle sum takes four table reads. The prefix-sum table and its rectangle query are in Chapter 34.

defOptimalLazyFinger.Preprocessing.Squareno axiomsAlgorithms/OptimalLazyFinger/Preprocessing/Definitions/Abstract.lean:10
/-- A dense square transition table. -/def Square (t : Table) (n : Nat) : Prop :=  t.size = n ∧ ∀ a < n, (t[a]?.getD #[]).size = n
defOptimalLazyFinger.Preprocessing.incrementno axiomsAlgorithms/OptimalLazyFinger/Preprocessing/Definitions/Abstract.lean:14
/-- Record one directed transition. -/def increment (t : Table) (a b : Nat) : Table :=  t.modify a (fun r => r.modify b (fun x => x + 1))
defOptimalLazyFinger.Preprocessing.fillno axiomsAlgorithms/OptimalLazyFinger/Preprocessing/Definitions/Abstract.lean:18
/-- Accumulate adjacent transitions in one pass over the requests. -/def fill : Table → Nat → List Nat → Table  | t, _, [] => t  | t, p, x :: xs => fill (increment t p x) x xs
defOptimalLazyFinger.Preprocessing.frequenciesno axiomsAlgorithms/OptimalLazyFinger/Preprocessing/Definitions/Abstract.lean:23
def frequencies (n p : Nat) (xs : List Nat) : Table :=  fill (Array.replicate n (Array.replicate n 0)) p xs

The matrix is a PrefixSum.Table, an array of rows. frequencies n p xs starts from the n×nn \times n zero matrix and makes one pass over the sequence, incrementing entry (xj−1,xj)(x_{j-1}, x_j) for each request, starting from x0=px_0 = p. increment uses Array.modify, which leaves the table unchanged at an index out of range. Square t n says that t has nn rows of length nn; the proofs use it as the invariant of the pass.

Theorem (transition counts). For all keys a,b<na, b < n, entry (a,b)(a, b) of the accumulated matrix is the directed adjacent-pair count LazyFinger.frequency p xs a b of Chapter 15, which includes the pair (p,x1)(p, x_1).

No hypothesis on pp or on the requests is needed: pairs with an endpoint outside {0,…,n−1}\{0, \dots, n-1\} are never stored, and the theorem only reads entries inside the matrix.

defOptimalLazyFinger.Preprocessing.preparepropextAlgorithms/OptimalLazyFinger/Preprocessing/Definitions/Abstract.lean:26
/-- Preprocessed transition prefixes, including any virtual initial key in `n`. -/def prepare (n p : Nat) (xs : List Nat) : Table :=  let f := frequencies n p xs  build (get f) n n
defOptimalLazyFinger.Preprocessing.tollno axiomsAlgorithms/OptimalLazyFinger/Preprocessing/Definitions/Abstract.lean:31
/-- Constant-number rectangle queries for traffic crossing `[lo,hi)`. -/def toll (p : Table) (n lo hi : Nat) : Nat :=  rectangle p lo hi 0 lo + rectangle p lo hi hi n +    rectangle p 0 lo lo hi + rectangle p hi n lo hi

prepare n p xs replaces the counts by their two-dimensional prefix sums, a table of (n+1)×(n+1)(n + 1) \times (n + 1) entries. toll computes the four rectangle sums above with PrefixSum.rectangle. The argument n of toll is the universe size, which gives the outer edges of the rectangles.

Theorem (prepared tolls). If the initial key pp and all requests are less than nn, then for every interval [lo,hi)[lo, hi) with lo≤hi≤nlo \le hi \le n, the prepared toll is the number of boundary crossings LazyFinger.crossings lo hi p xs.

theoremOptimalLazyFinger.Results.prepared_boundarypropext · Classical.choice · Quot.soundAlgorithms/OptimalLazyFinger/Abstract.lean:29
/-- Four prefix-sum rectangle queries return the exact sequence boundary toll. -/theorem prepared_boundary (n p : Nat) (xs : List Nat) (hp : p < n)    (valid : ∀ x ∈ xs, x < n) (lo hi : Nat) (hlo : lo ≤ hi) (hhi : hi ≤ n) :    Preprocessing.toll (Preprocessing.prepare n p xs) n lo hi = LazyFinger.crossings lo hi p xs :=  Preprocessing.toll_prepare n p xs hp valid lo hi hlo hhi

27.6 The optimizer

defOptimalLazyFinger.treeFrompropextAlgorithms/OptimalLazyFinger/Definitions/Abstract.lean:57
/-- Optimal tree for a given initial key and sequence, obtained from itspreprocessed interval boundary-crossing counts. The extra rank permits thevirtual initial key used by the root-start variant. -/def treeFrom (n p : Nat) (xs : List Nat) : Tree :=  let prepared := Preprocessing.prepare (n + 1) p xs  (optimize (Preprocessing.toll prepared (n + 1)) n).1
defOptimalLazyFinger.treepropextAlgorithms/OptimalLazyFinger/Definitions/Abstract.lean:64
/-- Root-start variant. The virtual key `n` makes the initialization penaltyindependent of the candidate tree's root. -/def tree (n : Nat) (xs : List Nat) : Tree := treeFrom n n xs

treeFrom n p xs prepares the transition table on a universe of n+1n + 1 keys, one more than the tree, and runs the interval optimizer on nn keys with the prepared tolls. The extra key nn never appears in a request. It is there for tree n xs, the root-start variant, which uses it as the virtual initial key of Section 27.2. For a specified start p<np < n, the extra key has no transitions and changes no toll.

Theorem (specified start). If p<np < n and every request is less than nn, then treeFrom n p xs has nn nodes, and its lazy-finger cost from pp is the optimum over all shapes with nn nodes.

Theorem (root start). If every request is less than nn, then tree n xs has nn nodes, and its lazy-finger cost, with the first search from the root, is the optimum over all shapes with nn nodes.

theoremOptimalLazyFinger.Results.root_startpropext · Classical.choice · Quot.soundAlgorithms/OptimalLazyFinger/Abstract.lean:42
/-- A constructive optimizer for the root-start benchmark, including the emptyuniverse and exact initialization cost. No asymptotic cost term is discarded. -/theorem root_start (n : Nat) (xs : List Nat) (valid : ∀ x ∈ xs, x < n) :    (tree n xs).size = n ∧ LazyFinger.cost (tree n xs) xs = LazyFinger.optimalCost n xs :=  ⟨tree_size n xs, tree_optimal n xs valid⟩

Both proofs combine the previous theorems. Within the interval [0,n+1)[0, n+1) the prepared tolls are the boundary crossings, so the interval cost the optimizer minimizes is the lazy-finger cost minus a constant, by the two identities of Section 27.2. Hence the returned tree is at most as costly as every shape of size nn, in particular as a shape attaining the infimum, which exists by Results.optimal_attained and Results.optimal_from_attained.

Reading the Lean
  • The optimum is over shapes with exactly nn nodes, the keys 0,…,n−10, \dots, n-1, and both costs charge one unit per request, as everywhere in Chapter 15. The equality is exact: no additive or multiplicative slack.
  • The root start is the paper’s model. The theorem covers n=0n = 0, where the only valid sequence is empty, and repeated requests, which cost one unit each.
  • The cost that optimize reports alongside the tree is the interval cost, not the lazy-finger cost; the two differ by mm, or by m−1m - 1 for the root start on a nonempty sequence. The theorems only use the tree.

27.7 A cost model for the work

Lean definitions have no running time of their own. A statement such as “the optimizer runs in O(m+n3)O(m + n^3) time” needs a model of computation, and the library makes it explicit: the counted optimizer is a second program, written in a monad that pairs each value with a natural-number count of the operations spent computing it.

defOptimalLazyFinger.Work.Computationno axiomsAlgorithms/OptimalLazyFinger/Work/Model/Abstract.lean:10
/-- Unit-cost RAM accounting. Scalar arithmetic/comparison, indexed array readsand updates, amortized append, and node allocation cost one. Control and listconstruction are charged by the traversals below. Values are mathematicalnaturals; this is not a bit-complexity or compiled-Lean runtime claim.As with `TimeM`, primitive cost annotations are part of the model. Algorithmloops use counted recursion; library allocation and traversal primitives receiveexplicit length-dependent charges. -/abbrev Computation (α : Type) := TimeM Nat α
defOptimalLazyFinger.Work.chargeno axiomsAlgorithms/OptimalLazyFinger/Work/Model/Abstract.lean:20
/-- A primitive or fixed straight-line block with its explicit charge. -/def charge {α : Type} (steps : Nat) (value : α) : Computation α := ⟨value, steps⟩

Computation α is TimeM Nat α from the CSLib library: a value ret together with a count time. Sequencing two computations adds their counts, and pure costs nothing. Counts are introduced only by charge steps value, which returns value at a cost of steps. The model is a unit-cost random-access machine:

  • a scalar addition, subtraction or comparison, an indexed array read or update, an amortized array append, and the allocation of a tree node each cost one;
  • values are mathematical natural numbers, each held in one machine word, so this is not a bit-complexity bound;
  • loops are counted recursions, and every step of a list traversal is charged.
defOptimalLazyFinger.Work.mapListno axiomsAlgorithms/OptimalLazyFinger/Work/Model/Abstract.lean:23
/-- Count every callback and list traversal step. -/def mapList {α β : Type} (f : α → Computation β) : List α → Computation (List β)  | [] => charge 1 []  | x :: xs => do      let y ← f x      let ys ← mapList f xs      charge 1 (y :: ys)
defOptimalLazyFinger.Work.arrayOfFnno axiomsAlgorithms/OptimalLazyFinger/Work/Model/Abstract.lean:31
/-- Explicit finite-array construction: enumerate indices, evaluate thecallbacks once, and convert the resulting list to an array. -/def arrayOfFn {α : Type} (n : Nat) (f : Fin n → Computation α) : Computation (Array α) := do  let indices ← charge (n + 1) (List.finRange n)  let values ← mapList f indices  charge (n + 1) values.toArray
defOptimalLazyFinger.Work.replicateno axiomsAlgorithms/OptimalLazyFinger/Work/Model/Abstract.lean:38
/-- Allocate and initialize a constant array. -/def replicate {α : Type} (n : Nat) (value : α) : Computation (Array α) :=  charge (n + 1) (Array.replicate n value)

These are the counted versions of the library primitives the optimizer uses. mapList f charges one unit per list cell, plus the counts of the callbacks. arrayOfFn n f charges n+1n + 1 to enumerate the indices, then the callbacks and the traversal through mapList, then n+1n + 1 to turn the list into an array. replicate n value charges n+1n + 1 to allocate and initialize an array of length nn.

Caveat

The charges are part of the model: they are written by hand in the program text, and the theorems bound their sum. Two things are proved about them. First, the counted program computes the same tree as the verified one (same_tree, in Section 27.9), so the counts describe the right computation. Second, the sum of the charges satisfies the stated bound. Whether each charge is a fair price for its operation is a judgement about the model, which the reader checks by reading the definitions in this section and the next. The theorems say nothing about the running time of the compiled Lean code. For example, Lean’s arrays are persistent, and an update that is charged one unit here may copy the array if it is shared.

27.8 The counted optimizer

The counted program mirrors the definitions of Section 27.3 to Section 27.6 step by step, with a charge on each primitive. It is a separate definition, so that the verified algorithm stays free of annotations.

Accumulating transitions. A matrix read is two indexed reads, one per level of the array of rows. An increment is two indexed updates and an addition. The pass over the requests charges one more step per request for the traversal, so it costs 4m+14m + 1 in all; this is the 4m4m of the bound. Allocating the zero matrix costs O(n2)O(n^2).

defOptimalLazyFinger.Work.rowno axiomsAlgorithms/OptimalLazyFinger/Work/Definitions/Abstract.lean:28
/-- The input row itself may be a counted lookup computation. -/def row (f : Nat → Computation Nat) : Nat → Computation (Array Nat)  | 0 => charge 1 #[0]  | n + 1 => do      let previous ← row f n      let x ← f n      charge 4 (previous.push (previous[n]?.getD 0 + x))
defOptimalLazyFinger.Work.buildno axiomsAlgorithms/OptimalLazyFinger/Work/Definitions/Abstract.lean:36
def build (f : Nat → Nat → Computation Nat) (width : Nat) : Nat → Computation PrefixSum.Table  | 0 => do      let zeros ← replicate (width + 1) 0      charge 1 #[zeros]  | height + 1 => do      let previous ← build f width height      let horizontal ← row (f height) width      let next ← arrayOfFn (width + 1) (fun b =>        charge 4 (PrefixSum.get previous height b.val + horizontal[b.val]?.getD 0))      charge 2 (previous.push next)
defOptimalLazyFinger.Work.prepareno axiomsAlgorithms/OptimalLazyFinger/Work/Definitions/Abstract.lean:47
def prepare (n p : Nat) (xs : List Nat) : Computation PrefixSum.Table := do  let f ← frequencies n p xs  build (matrixGet f) n n

Prefix sums. row computes the prefix sums of one row, charging 44 per entry for the read of the previous prefix, the addition and the append, plus the reads of the input. build adds each row’s prefixes to those of the previous row, at 44 per entry plus the array construction. Here the input entries are themselves counted matrix reads: prepare passes matrixGet of the transition matrix.

defOptimalLazyFinger.Work.rectangleno axiomsAlgorithms/OptimalLazyFinger/Work/Definitions/Abstract.lean:51
/-- Four matrix reads and three arithmetic operations. -/def rectangle (p : PrefixSum.Table) (a b c d : Nat) : Computation Nat :=  charge 11 (PrefixSum.rectangle p a b c d)
defOptimalLazyFinger.Work.tollno axiomsAlgorithms/OptimalLazyFinger/Work/Definitions/Abstract.lean:55
/-- Four rectangle queries and three additions: 47 RAM operations. -/def toll (p : PrefixSum.Table) (n lo hi : Nat) : Computation Nat := do  let a ← rectangle p lo hi 0 lo  let b ← rectangle p lo hi hi n  let c ← rectangle p 0 lo lo hi  let d ← rectangle p hi n lo hi  charge 3 (a + b + c + d)

Tolls. A rectangle query is four two-level reads and three arithmetic operations, 1111 units; a toll is four rectangle queries and three additions, 4747 units, whatever the interval.

defOptimalLazyFinger.Work.minimumno axiomsAlgorithms/OptimalLazyFinger/Work/Definitions/Abstract.lean:63
def minimum (initial : Entry) : List Entry → Computation Entry  | [] => charge 1 initial  | x :: xs => do      let tail ← minimum initial xs      charge 2 (choose x tail)
defOptimalLazyFinger.Work.candidateno axiomsAlgorithms/OptimalLazyFinger/Work/Definitions/Abstract.lean:69
/-- Five index arithmetic operations, two two-level table reads, two costadditions, and a shape node allocation, in addition to the toll computation. -/def candidate (w : Nat → Nat → Computation Nat) (previous : Array (Array Entry))    (n lo k : Nat) : Computation Entry := do  let cost ← w lo (lo + n + 1)  let l := lookup previous k lo  let r := lookup previous (n - k) (lo + k + 1)  charge 12 (.node l.1 r.1, cost + l.2 + r.2)
defOptimalLazyFinger.Work.cellpropextAlgorithms/OptimalLazyFinger/Work/Definitions/Abstract.lean:78
/-- One cached DP cell, including the extra initial candidate used by `minimum`. -/def cell (w : Nat → Nat → Computation Nat) (previous : Array (Array Entry))    (N n lo : Nat) : Computation Entry := do  let valid ← charge 3 (decide (lo + n + 1 ≤ N))  if valid then    let first ← candidate w previous n lo 0    let indices ← charge (n + 2) (List.finRange (n + 1))    let choices ← mapList (fun k => candidate w previous n lo k.val) indices    minimum first choices  else pure (.nil, 0)
defOptimalLazyFinger.Work.tabulatepropextAlgorithms/OptimalLazyFinger/Work/Definitions/Abstract.lean:89
def tabulate (w : Nat → Nat → Computation Nat) (N : Nat) : Nat → Computation (Array (Array Entry))  | 0 => do      let zeros ← replicate (N + 1) (.nil, 0)      charge 1 #[zeros]  | n + 1 => do      let previous ← tabulate w N n      let next ← arrayOfFn (N + 1) (fun lo => cell w previous N n lo.val)      charge 2 (previous.push next)
defOptimalLazyFinger.Work.optimizepropextAlgorithms/OptimalLazyFinger/Work/Definitions/Abstract.lean:98
def optimize (w : Nat → Nat → Computation Nat) (n : Nat) : Computation Entry := do  let table ← tabulate w n n  charge 2 (lookup table n 0)

The table. The counted minimum charges a comparison and a step per candidate. candidate computes the toll, which may itself be a counted computation, and charges 1212 for the index arithmetic, the two table lookups, the two additions and the allocation of one tree node. The node shares its two subtrees with the table, as a pointer machine would, so building a candidate tree costs one allocation, not a copy. cell charges 33 to test whether the interval fits in the universe. A valid cell evaluates the first candidate as the fold’s initial value, enumerates the n+1n+1 root choices, evaluates each candidate and folds. An invalid cell stops after the test. tabulate and optimize mirror their uncounted versions. Every row has N+1N + 1 cells, so there are O(N2)O(N^2) cells, each with O(N)O(N) candidates at constant cost: the 64(n+1)364(n+1)^3 of the bound.

defOptimalLazyFinger.Work.treeFrompropextAlgorithms/OptimalLazyFinger/Work/Definitions/Abstract.lean:102
/-- Counted executable optimizer, including preprocessing and initialization. -/def treeFrom (n p : Nat) (xs : List Nat) : Computation Tree := do  let prepared ← prepare (n + 1) p xs  let result ← optimize (toll prepared (n + 1)) n  pure result.1
defOptimalLazyFinger.Work.treepropextAlgorithms/OptimalLazyFinger/Work/Definitions/Abstract.lean:108
def tree (n : Nat) (xs : List Nat) : Computation Tree := treeFrom n n xs

Work.treeFrom and Work.tree are the whole counted optimizer, including the preprocessing on n+1n + 1 keys and the virtual initial key. Their time is the end-to-end work.

27.9 The work bound

Theorem (erasure). Forgetting the counts, the counted optimizer returns exactly the tree of the verified optimizer, for every input.

Theorem (preprocessing). Accumulating the transitions and computing the prefix sums on a universe of nn keys costs at most 4m+14n2+18n+74m + 14n^2 + 18n + 7.

The optimizer calls the preprocessing on n+1n + 1 keys, with the virtual key. No hypothesis on the requests is needed: the counts do not depend on the values of the requests, only on their number.

Theorem 8 (exact optimizer, root start). If every request is less than nn, the counted root-start optimizer returns a tree with nn nodes, its lazy-finger cost is the optimum over all shapes with nn nodes, and its work is at most 4m+64(n+1)34m + 64(n+1)^3.

theoremOptimalLazyFinger.Work.Results.root_startpropext · Classical.choice · Quot.soundAlgorithms/OptimalLazyFinger/Work/Abstract.lean:18
/-- Exact optimality and an end-to-end cubic work bound, in the cost model of`Work.Model.Abstract`. This includes root initialization and empty instances. -/theorem root_start (n : Nat) (xs : List Nat) (valid : ∀ x ∈ xs, x < n) :    (tree n xs).ret.size = n ∧      LazyFinger.cost (tree n xs).ret xs = LazyFinger.optimalCost n xs ∧      (tree n xs).time ≤ 4 * xs.length + 64 * (n + 1) ^ 3 := tree_spec n xs valid

Theorem (specified start). If p<np < n and every request is less than nn, the counted optimizer from pp returns a tree with nn nodes whose lazy-finger cost from pp is optimal, with work at most 4m+64(n+1)34m + 64(n+1)^3.

The correctness parts are the theorems of Section 27.6, transported through the erasure theorem. The work part adds the preprocessing bound to the cost of the table: nn rows of n+1n + 1 cells, each evaluating at most n+2n + 2 candidates (the n+1n + 1 root choices and the fold’s initial value) at 47+1247 + 12 units each, plus constant overhead.

Theorem (the usual form). On a nonempty universe, the work is at most 4m+512 n34m + 512\,n^3, that is, O(m+n3)O(m + n^3).

This is the previous bound with (n+1)3≤8n3(n+1)^3 \le 8n^3 for n≥1n \ge 1. Like the preprocessing bound, it holds for every input, valid or not.

Where the cubic term comes from

The table evaluates every pair (length, start), (N+1)2(N + 1)^2 cells per stage, although only about half of them are valid intervals, and the invalid ones cost only their validity test. The constant 6464 is therefore not tight; the bound is meant to be simple, explicit and end-to-end, including preprocessing, initialization and the empty universe.