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 for requests on keys.
Let be a sequence of keys from . A static BST on these keys serves with a lazy finger at cost
where is the number of edges on the path between and in , and is the root of : one unit per request, plus the edges the finger walks. There is an explicit algorithm that, given and , returns a tree with nodes such that
and whose work, counted in an explicit unit-cost RAM model, is at most . The bound holds for every , including , with no hidden constants. The same holds when the first search starts from a specified key instead of the root, that is, with .
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 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
/-- 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 validModels.Rotation, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Bounds.LazyFinger.Edges.Definitions, Bounds.LazyFinger.Frequencies.Definitions, Structures.PrefixSum.Definitions, Algorithms.OptimalLazyFinger.Definitions, Algorithms.OptimalLazyFinger.Preprocessing.Definitions, Algorithms.OptimalLazyFinger.Work.Model, Algorithms.OptimalLazyFinger.Work.Definitions/-- 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 validModels.Rotation, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Bounds.LazyFinger.Edges.Definitions, Bounds.LazyFinger.Frequencies.Definitions, Structures.PrefixSum.Definitions, Algorithms.OptimalLazyFinger.Definitions, Algorithms.OptimalLazyFinger.Preprocessing.Definitions, Algorithms.OptimalLazyFinger.Work.Model, Algorithms.OptimalLazyFinger.Work.DefinitionsTo 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.
- 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.
- Interval dynamic programming. For any toll on half-open intervals, the shape minimizing satisfies Bellman’s recurrence over intervals. A table indexed by interval length and start computes it with choices for each of intervals: .
- Tolls in constant time. The toll of is a sum of the transition counts , the number of times the request sequence moves from key to key , over four rectangles of the matrix . After one pass over the sequence to fill , in , and two-dimensional prefix sums, in , each toll costs four rectangle queries.
- Root start. A virtual extra key , outside every subtree, plays the previous request of . 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 when exactly one of two keys lies in a half-open interval , and LazyFinger.crossings, which sums cut lo hi over the consecutive pairs of a sequence with an explicit initial key . The cost of a shape is then LazyFinger.intervalCost w t lo: the sum of over the key intervals 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 inside the tree, Results.sequence says
The whole tree’s interval contains every key, so its toll is and only proper subtrees, that is edges, contribute. For the root start, Results.initialization takes the virtual initial key , which lies outside every subtree. The first transition then crosses the boundary of every subtree that contains , which is subtrees, while the root-start search for walks edges. So
where is for a nonempty sequence. In both cases, the lazy-finger cost and the interval cost differ by a quantity that does not depend on . A shape minimizing one minimizes the other.
27.3 Bellman’s recurrence
The interval problem is: given a toll , find a shape with 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 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 for the optimum on the keys ,
where is the number of keys in the left subtree, so the root is key .
/-- A constructed shape paired with its boundary-toll cost. -/abbrev Entry := Tree × Nat/-- 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/-- Fold a finite family of candidates with a supplied initial candidate. -/def minimum (initial : Entry) (candidates : List Entry) : Entry := candidates.foldr choose initialAn 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.
/-- 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 omegasolve 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.
/-- 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)/-- 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))/-- 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 0tabulate w univSize stages builds rows . Row has one entry for every start ; the entry is the solution on the interval if that interval fits in the universe, and the placeholder (.nil, 0) otherwise. Row is all empty trees. Row 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 keys and reads the entry for the whole interval .
Theorem (cached recurrence). For every toll , every valid interval, of length at most the number of rows built and with , the table entry is exactly the recursive solution, including the shape chosen among ties.
/-- 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 validModels.Rotation, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Bounds.LazyFinger.Edges.Definitions, Algorithms.OptimalLazyFinger.Definitions, Algorithms.OptimalLazyFinger.Preprocessing.Definitions, Bounds.LazyFinger.Frequencies.Definitions, Structures.PrefixSum.DefinitionsTheorem (the interval optimizer). For every toll and every , optimize w n returns a shape with nodes, its reported cost is the shape’s interval cost, and no shape with nodes has a smaller interval cost.
/-- 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 nModels.Rotation, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Bounds.LazyFinger.Edges.Definitions, Algorithms.OptimalLazyFinger.Definitions, Algorithms.OptimalLazyFinger.Preprocessing.Definitions, Bounds.LazyFinger.Frequencies.Definitions, Structures.PrefixSum.DefinitionsThe toll is arbitrary here: any function of the interval endpoints. This is the general form of the classical optimal-BST recurrence. For instance, with the total access frequency of the keys in , 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 for each of the intervals. Instead, the optimizer summarizes the sequence once, in the matrix of directed transition counts , with the initial key as . A pair crosses the boundary of exactly when one endpoint is inside and the other is outside, to the left or to the right, so
where is the sum of the entries with row in and column in . 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 , each rectangle sum takes four table reads. The prefix-sum table and its rectangle query are in Chapter 34.
/-- A dense square transition table. -/def Square (t : Table) (n : Nat) : Prop := t.size = n ∧ ∀ a < n, (t[a]?.getD #[]).size = n/-- Record one directed transition. -/def increment (t : Table) (a b : Nat) : Table := t.modify a (fun r => r.modify b (fun x => x + 1))/-- 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 xsdef frequencies (n p : Nat) (xs : List Nat) : Table := fill (Array.replicate n (Array.replicate n 0)) p xsThe matrix is a PrefixSum.Table, an array of rows. frequencies n p xs starts from the zero matrix and makes one pass over the sequence, incrementing entry for each request, starting from . increment uses Array.modify, which leaves the table unchanged at an index out of range. Square t n says that t has rows of length ; the proofs use it as the invariant of the pass.
Theorem (transition counts). For all keys , entry of the accumulated matrix is the directed adjacent-pair count LazyFinger.frequency p xs a b of Chapter 15, which includes the pair .
/-- The one-pass array accumulator stores the directed adjacent-pair counts. -/theorem pair_frequencies (n p : Nat) (xs : List Nat) (i j : Nat) (hi : i < n) (hj : j < n) : PrefixSum.get (Preprocessing.frequencies n p xs) i j = LazyFinger.frequency p xs i j := Preprocessing.get_frequencies n p xs i j hi hjModels.Rotation, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Bounds.LazyFinger.Edges.Definitions, Algorithms.OptimalLazyFinger.Definitions, Algorithms.OptimalLazyFinger.Preprocessing.Definitions, Bounds.LazyFinger.Frequencies.Definitions, Structures.PrefixSum.DefinitionsNo hypothesis on or on the requests is needed: pairs with an endpoint outside are never stored, and the theorem only reads entries inside the matrix.
/-- 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/-- 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 hiprepare n p xs replaces the counts by their two-dimensional prefix sums, a table of 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 and all requests are less than , then for every interval with , the prepared toll is the number of boundary crossings LazyFinger.crossings lo hi p xs.
/-- 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 hhiModels.Rotation, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Bounds.LazyFinger.Edges.Definitions, Algorithms.OptimalLazyFinger.Definitions, Algorithms.OptimalLazyFinger.Preprocessing.Definitions, Bounds.LazyFinger.Frequencies.Definitions, Structures.PrefixSum.Definitions27.6 The optimizer
/-- 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/-- 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 xstreeFrom n p xs prepares the transition table on a universe of keys, one more than the tree, and runs the interval optimizer on keys with the prepared tolls. The extra key 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 , the extra key has no transitions and changes no toll.
Theorem (specified start). If and every request is less than , then treeFrom n p xs has nodes, and its lazy-finger cost from is the optimum over all shapes with nodes.
/-- A constructive optimizer for lazy finger 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).size = n ∧ LazyFinger.costFrom (treeFrom n p xs) p xs = LazyFinger.optimalCostFrom n p xs := ⟨treeFrom_size n p xs, treeFrom_optimal n p xs hp valid⟩Models.Rotation, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Bounds.LazyFinger.Edges.Definitions, Algorithms.OptimalLazyFinger.Definitions, Algorithms.OptimalLazyFinger.Preprocessing.Definitions, Bounds.LazyFinger.Frequencies.Definitions, Structures.PrefixSum.DefinitionsTheorem (root start). If every request is less than , then tree n xs has nodes, and its lazy-finger cost, with the first search from the root, is the optimum over all shapes with nodes.
/-- 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⟩Models.Rotation, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Bounds.LazyFinger.Edges.Definitions, Algorithms.OptimalLazyFinger.Definitions, Algorithms.OptimalLazyFinger.Preprocessing.Definitions, Bounds.LazyFinger.Frequencies.Definitions, Structures.PrefixSum.DefinitionsBoth proofs combine the previous theorems. Within the interval 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 , in particular as a shape attaining the infimum, which exists by Results.optimal_attained and Results.optimal_from_attained.
- The optimum is over shapes with exactly nodes, the keys , 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 , where the only valid sequence is empty, and repeated requests, which cost one unit each.
- The cost that
optimizereports alongside the tree is the interval cost, not the lazy-finger cost; the two differ by , or by 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 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.
/-- 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 α/-- 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.
/-- 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)/-- 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/-- 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 to enumerate the indices, then the callbacks and the traversal through mapList, then to turn the list into an array. replicate n value charges to allocate and initialize an array of length .
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.
/-- One read at each level of a dense matrix. -/def matrixGet (t : PrefixSum.Table) (a b : Nat) : Computation Nat := charge 2 (PrefixSum.get t a b)/-- Two indexed updates and one scalar increment. -/def increment (t : PrefixSum.Table) (a b : Nat) : Computation PrefixSum.Table := charge 3 (Preprocessing.increment t a b)def fill : PrefixSum.Table → Nat → List Nat → Computation PrefixSum.Table | t, _, [] => charge 1 t | t, p, x :: xs => do let next ← increment t p x let result ← fill next x xs charge 1 resultdef frequencies (n p : Nat) (xs : List Nat) : Computation PrefixSum.Table := do let zeros ← arrayOfFn n (fun _ => replicate n 0) fill zeros p xsAccumulating 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 in all; this is the of the bound. Allocating the zero matrix costs .
/-- 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))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)def prepare (n p : Nat) (xs : List Nat) : Computation PrefixSum.Table := do let f ← frequencies n p xs build (matrixGet f) n nPrefix sums. row computes the prefix sums of one row, charging 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 per entry plus the array construction. Here the input entries are themselves counted matrix reads: prepare passes matrixGet of the transition matrix.
/-- 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)/-- 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, units; a toll is four rectangle queries and three additions, units, whatever the interval.
def minimum (initial : Entry) : List Entry → Computation Entry | [] => charge 1 initial | x :: xs => do let tail ← minimum initial xs charge 2 (choose x tail)/-- 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)/-- 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)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)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 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 to test whether the interval fits in the universe. A valid cell evaluates the first candidate as the fold’s initial value, enumerates the root choices, evaluates each candidate and folds. An invalid cell stops after the test. tabulate and optimize mirror their uncounted versions. Every row has cells, so there are cells, each with candidates at constant cost: the of the bound.
/-- 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.1def tree (n : Nat) (xs : List Nat) : Computation Tree := treeFrom n n xsWork.treeFrom and Work.tree are the whole counted optimizer, including the preprocessing on 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.
/-- Erasing the annotations yields exactly the existing executable optimizer. -/theorem same_tree (n p : Nat) (xs : List Nat) : (treeFrom n p xs).ret = OptimalLazyFinger.treeFrom n p xs := treeFrom_ret n p xsModels.Rotation, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Bounds.LazyFinger.Edges.Definitions, Bounds.LazyFinger.Frequencies.Definitions, Structures.PrefixSum.Definitions, Algorithms.OptimalLazyFinger.Definitions, Algorithms.OptimalLazyFinger.Preprocessing.Definitions, Algorithms.OptimalLazyFinger.Work.Model, Algorithms.OptimalLazyFinger.Work.DefinitionsTheorem (preprocessing). Accumulating the transitions and computing the prefix sums on a universe of keys costs at most .
/-- Transition accumulation and prefix preprocessing cost linearly in therequest count and quadratically in the stored universe size. -/theorem preprocessing (n p : Nat) (xs : List Nat) : (prepare n p xs).time ≤ 4 * xs.length + 14 * n ^ 2 + 18 * n + 7 := prepare_time n p xsModels.Rotation, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Bounds.LazyFinger.Edges.Definitions, Bounds.LazyFinger.Frequencies.Definitions, Structures.PrefixSum.Definitions, Algorithms.OptimalLazyFinger.Definitions, Algorithms.OptimalLazyFinger.Preprocessing.Definitions, Algorithms.OptimalLazyFinger.Work.Model, Algorithms.OptimalLazyFinger.Work.DefinitionsThe optimizer calls the preprocessing on 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 , the counted root-start optimizer returns a tree with nodes, its lazy-finger cost is the optimum over all shapes with nodes, and its work is at most .
/-- 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 validModels.Rotation, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Bounds.LazyFinger.Edges.Definitions, Bounds.LazyFinger.Frequencies.Definitions, Structures.PrefixSum.Definitions, Algorithms.OptimalLazyFinger.Definitions, Algorithms.OptimalLazyFinger.Preprocessing.Definitions, Algorithms.OptimalLazyFinger.Work.Model, Algorithms.OptimalLazyFinger.Work.DefinitionsTheorem (specified start). If and every request is less than , the counted optimizer from returns a tree with nodes whose lazy-finger cost from is optimal, with work at most .
/-- 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 validModels.Rotation, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Bounds.LazyFinger.Edges.Definitions, Bounds.LazyFinger.Frequencies.Definitions, Structures.PrefixSum.Definitions, Algorithms.OptimalLazyFinger.Definitions, Algorithms.OptimalLazyFinger.Preprocessing.Definitions, Algorithms.OptimalLazyFinger.Work.Model, Algorithms.OptimalLazyFinger.Work.DefinitionsThe 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: rows of cells, each evaluating at most candidates (the root choices and the fold’s initial value) at units each, plus constant overhead.
Theorem (the usual form). On a nonempty universe, the work is at most , that is, .
/-- The usual `O(m+n³)` form on nonempty universes, as an explicit inequality. -/theorem nonempty_bound (n p : Nat) (xs : List Nat) (hn : 0 < n) : (treeFrom n p xs).time ≤ 4 * xs.length + 512 * n ^ 3 := treeFrom_time_nonempty n p xs hnModels.Rotation, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Bounds.LazyFinger.Edges.Definitions, Bounds.LazyFinger.Frequencies.Definitions, Structures.PrefixSum.Definitions, Algorithms.OptimalLazyFinger.Definitions, Algorithms.OptimalLazyFinger.Preprocessing.Definitions, Algorithms.OptimalLazyFinger.Work.Model, Algorithms.OptimalLazyFinger.Work.DefinitionsThis is the previous bound with for . Like the preprocessing bound, it holds for every input, valid or not.
The table evaluates every pair (length, start), cells per stage, although only about half of them are valid intervals, and the invalid ones cost only their validity test. The constant is therefore not tight; the bound is meant to be simple, explicit and end-to-end, including preprocessing, initialization and the empty universe.