Chapter 15The lazy and the (weighted) dynamic finger
A static binary search tree never changes shape. The classical way to search it, the root finger, starts every search at the root, so a search for costs the depth of . Its optimum is well understood: the best static tree serves a sequence in time proportional to plus the entropy of the access frequencies (Chapter 14). Bose, Douïeb, Iacono and Langerman (2016) studied a different way to search the same tree, the lazy finger: each search starts where the previous one ended. To go from to , the finger climbs from to their lowest common ancestor and descends to . Up to a factor of two, lazy finger is at least as good as root finger: the walk through the LCA is never longer than the walk up to the root and down again, which costs at most twice a root-finger search. And it is no better than a BST with rotations, which can simulate it. Between those two, it can be much better than root finger: a sequential scan of length costs with a lazy finger in every tree, but with a root finger in every tree.
The optimal root-finger cost is a function of the access frequencies alone. The optimal lazy-finger cost depends on the frequencies of consecutive pairs. The natural entropy of those, the conditional entropy, is not the answer: the paper shows that no BST, static or not, is bounded by it within any constant factor and additive startup term (Chapter 18). What does capture it is the weighted dynamic finger bound of Iacono and Langerman (2016): give every key a positive weight , and charge a move from to
The paper’s main theorem, its Theorem 5, says that the best static tree with a lazy finger costs, up to constant factors, exactly as much as the best choice of weights. This chapter formalizes it, together with the four results it is assembled from: a random tree that realizes any weights (Theorem 1), the tree that this gives for a given sequence (Corollary 2), and the weights that represent a given tree (Lemma 3 and Corollary 4).
Let be requests to the keys , and let be a starting key. Write for the number of edges between and in a tree , and . Define, with ,
the minimum over all binary search trees on the keys, and the infimum over all weightings that are positive on the keys. Let be defined like , except that the first search starts at the root of . Then
and, for the root start, with an additive for the initial position,
If , the additive term is not needed: and .
Both costs charge one unit per request, and the minimum over trees is attained. In Lean, is LazyFinger.optimalCostFrom, is LazyFinger.optimalCost, and is WeightedFinger.optimalCostFrom.
The Lean statements
/-- Weight/tree characterization with the same specified initial key on bothsides. The tree minimum is attained; the weight benchmark is an infimum. -/theorem characterization_from (n p : Nat) (xs : List Nat) (hp : p < n) (valid : ∀ x ∈ xs, x < n) : WeightedFinger.optimalCostFrom n p xs ≤ 3 * (optimalCostFrom n p xs : ℝ) ∧ (optimalCostFrom n p xs : ℝ) ≤ 4 * WeightedFinger.optimalCostFrom n p xs := … optimal_from_characterization n p xs hp valid/-- Adding the startup allowance `n` makes the benchmarks factor-four equivalent. -/theorem characterization (n p : Nat) (xs : List Nat) (hp : p < n) (valid : ∀ x ∈ xs, x < n) : (optimalCost n xs : ℝ) + n ≤ 4 * (WeightedFinger.optimalCostFrom n p xs + n) ∧ WeightedFinger.optimalCostFrom n p xs + n ≤ 4 * ((optimalCost n xs : ℝ) + n) := … characterization_with_startup n p xs hp valid/-- When `m ≥ n`, no separate additive startup term is needed. -/theorem characterization_long_sequence (n p : Nat) (xs : List Nat) (hp : p < n) (valid : ∀ x ∈ xs, x < n) (long : n ≤ xs.length) : WeightedFinger.optimalCostFrom n p xs ≤ 6 * (optimalCost n xs : ℝ) ∧ (optimalCost n xs : ℝ) ≤ 5 * WeightedFinger.optimalCostFrom n p xs := … characterization_long n p xs hp valid longWith the notation of the previous box, write for the lazy-finger cost of one tree from , for the weighted charge, and .
- Weights give a tree (Corollary 2). For every weighting positive on , every and every sequence of keys less than , there is a tree on the keys with . The tree may depend on and on .
- Trees give weights (Lemma 3). For every tree there is one weighting , positive everywhere, such that for all keys of , and hence, for every valid start and sequence , .
- The reverse comparison (Corollary 4) is the upper half: and .
In Lean, is LazyFinger.costFrom, is WeightedFinger.charge and is WeightedFinger.costFrom.
The Lean statements
/-- Weights-to-tree direction of the lazy-finger characterization, with anexplicit initial finger and normalized request charges. A single fixed treeserves the entire sequence; its choice may depend on the weights and sequence. -/theorem tree_for_weights (w : Nat → ℝ) (n p : Nat) (xs : List Nat) (hw : ∀ k < n, 0 < w k) (hp : p < n) (valid : ∀ x ∈ xs, x < n) : ∃ t : Tree, t.size = n ∧ (costFrom t p xs : ℝ) ≤ 4 * WeightedFinger.costFrom w p xs := … exists_tree_for_weights w n p xs hw hp valid/-- Both pairwise and sequence comparisons use the same positive weights. -/theorem tree_weights_two_sided (t : Tree) : ∃ w : Nat → ℝ, (∀ x, 0 < w x) ∧ (∀ x y, x < t.size → y < t.size → 1 + (distance t x y : ℝ) ≤ WeightedFinger.charge w x y ∧ WeightedFinger.charge w x y ≤ 3 + 2 * (distance t x y : ℝ)) ∧ (∀ p xs, p < t.size → (∀ x ∈ xs, x < t.size) → (costFrom t p xs : ℝ) ≤ WeightedFinger.costFrom w p xs ∧ WeightedFinger.costFrom w p xs ≤ 3 * (costFrom t p xs : ℝ)) := … exists_two_sided_weights t/-- Tree-to-weights direction of the characterization in §3 ofarXiv:1304.6897, with explicit constants and normalized request charges.One positive weighting works for every valid pair and every valid sequenceon this tree. The converse weights-to-tree direction is separate. -/theorem tree_weights (t : Tree) : ∃ w : Nat → ℝ, (∀ x, 0 < w x) ∧ (∀ x y, x < t.size → y < t.size → WeightedFinger.charge w x y ≤ 3 + 2 * (distance t x y : ℝ)) ∧ (∀ p xs, p < t.size → (∀ x ∈ xs, x < t.size) → WeightedFinger.costFrom w p xs ≤ 3 * (costFrom t p xs : ℝ)) := … exists_weights_for_tree tLet be positive on . Draw a random order of the keys by repeatedly choosing one of the remaining keys with probability proportional to its weight. There is an assignment of a tree on the keys to every order such that, for all keys ,
The assignment depends on and only, so one random tree serves every pair at once. This is Theorem 1 of the paper, which attributes it to Seidel and Aragon (1996); in the proof, is the treap whose priority order is . In Lean, the expectation is Random.average and the right side is times WeightedFinger.charge.
The Lean statement
/-- The same random family satisfies the weighted dynamic-finger bound forall pairs. This counts one request plus movement and uses base-two logarithms. -/theorem weighted_charge (w : Nat → ℝ) (n : Nat) (hw : ∀ k < n, 0 < w k) : ∃ T : List Nat → Tree, (∀ xs, (T xs).size = n) ∧ ∀ x y, x < n → y < n → average w (Finset.range n) (fun xs => 1 + (distance (T xs) x y : ℝ)) ≤ 4 * WeightedFinger.charge w x y := … exists_expected_charge_bound w n hwThe first box is the paper’s Theorem 5; the second and third are the steps of its proof. To confirm them, a reader needs only the tree shapes and depths of Chapter 1, the lazy-finger distance and costs of Section 15.1 and Section 15.3, the weighted charge of Section 15.5, and, for the third box, the weighted sampling of Chapter 32. The checking page lists the exact reading path of each.
The rest of the chapter goes through these definitions in order and states every theorem again, in English before its Lean form. Section 15.1 defines the distance between two keys in a fixed tree, and Section 15.2 recounts it with ancestors, the form used for random trees. Section 15.3 and Section 15.4 define the lazy-finger cost and its optimum, and compare them with root finger. Section 15.5 defines the weighted charge. Section 15.6 proves Theorem 1, Section 15.7 the two directions between weights and trees, and Section 15.8 assembles Theorem 5. The last section, Section 15.9, rewrites the cost as a sum over the subtrees of the tree. It is not needed for Theorem 5; it is the form in which Chapter 27 computes the optimal tree by dynamic programming. The results that place lazy finger between root finger and rotations, and the consequences of the characterization, are in Chapter 16.
The definitions are in Bounds/LazyFinger/Definitions/Abstract.lean, Bounds/WeightedFinger/Definitions/Abstract.lean, Bounds/LazyFinger/Edges/Definitions/Abstract.lean and Bounds/LazyFinger/Frequencies/Definitions/Abstract.lean, and search paths in Models/Rotation/Search/Abstract.lean. The theorems are in the Abstract.lean files of Bounds/LazyFinger, Bounds/WeightedFinger, Bounds/LazyFinger/Random and Bounds/LazyFinger/Edges.
15.1 Distance in a fixed tree
Keys are ranks, as everywhere in the library (Chapter 1): a tree on nodes holds the keys in inorder, and the root of node l r is the rank l.size. The paper writes for the time to move a pointer from to ; the library calls it the distance.
/-- Edge distance between ranks in a fixed BST: descend together until thelowest common ancestor, then add the two remaining depths. Invalid ranks onlyhave totalized values; applications use ranks less than `t.size`. -/def distance : Tree → Nat → Nat → Nat | .nil, _, _ => 0 | .node l r, x, y => if x < l.size ∧ y < l.size then distance l x y else if l.size < x ∧ l.size < y then distance r (x - l.size - 1) (y - l.size - 1) else Tree.depth (.node l r) x + Tree.depth (.node l r) yIf both ranks lie in the left subtree, or both strictly in the right subtree (with ranks shifted by l.size + 1), the path between them stays in that subtree, and the recursion follows it. Otherwise the root separates them, or is one of them. Then the root is their lowest common ancestor, and the path goes up from to the root and down to , so its length is the sum of the two depths. Depth is Tree.depth (Chapter 1), with the root at depth , so the distance from a key to itself is and the distance between a parent and a child is .
- The distance counts edges, not nodes. The cost of a search adds one unit for the request itself (Section 15.3).
- On ranks that are not keys of the tree,
distancestill returns a number, because every Lean function is total, but that number means nothing. Every theorem that uses it either holds for all ranks or assumes valid ones.
The depth of the lowest common ancestor is defined by the same recursion:
/-- Depth of the lowest common ancestor of two valid ranks. -/def lcaDepth : Tree → Nat → Nat → Nat | .nil, _, _ => 0 | .node l r, x, y => if x < l.size ∧ y < l.size then lcaDepth l x y + 1 else if l.size < x ∧ l.size < y then lcaDepth r (x - l.size - 1) (y - l.size - 1) + 1 else 0The definitions fit together as in the paper’s formula .
Theorem (LCA identity). For every tree and all ranks , .
/-- Exact relation between movement distance, depths, and the lowest commonancestor. This is the identity used in §1.2 of the lazy-finger paper. -/theorem lca_identity (t : Tree) (x y : Nat) : distance t x y + 2 * lcaDepth t x y = Tree.depth t x + Tree.depth t y := distance_add_twice_lca t x yThe identity has no hypotheses: the three totalized functions descend in lockstep, so it holds even on invalid ranks. It is stated with the subtraction moved to the other side, to stay in natural numbers.
Distance behaves like a metric on the keys. It is symmetric, it vanishes on the diagonal, and it vanishes nowhere else.
Theorem (basic properties). For every tree : for all ; for every key ; and for keys , exactly when .
theorem symmetric (t : Tree) (x y : Nat) : distance t x y = distance t y x := distance_symm t x ytheorem repeated_key (t : Tree) (x : Nat) (hx : x < t.size) : distance t x x = 0 := distance_self t x hx/-- Zero movement identifies equal keys on the valid key domain. -/theorem zero_distance (t : Tree) (x y : Nat) (hx : x < t.size) (hy : y < t.size) : distance t x y = 0 ↔ x = y := distance_eq_zero_iff t x y hx hyThe triangle inequality also holds, since is a path length in a tree, but it is not part of the reading interface.
15.2 Search paths and ancestors
A second description of the distance counts nodes instead of edges. Every node on the path between and is an ancestor of exactly one of them, apart from their common ancestors, which the path avoids above the LCA. This is the description that makes random trees tractable, because the probability that one key is an ancestor of another has a closed form (Section 15.6).
The library describes the ancestors of by the search path to :
/-- Root-to-key search path in a shape whose inorder ranks start at `lo`.Includes both root and requested key on valid inputs. Out-of-range requestsare totalized by following the corresponding unsuccessful search path. -/def searchPath : Tree → Nat → Nat → List Nat | .nil, _, _ => [] | .node l r, lo, x => let root := lo + l.size if x < root then root :: searchPath l lo x else if x = root then [root] else root :: searchPath r (root + 1) xsearchPath t lo x lists the keys visited by an ordinary root-to-leaf search for , in a tree whose inorder ranks start at lo, so that its root is lo + l.size. The search compares with the root and stops there, or continues left or right. The offset lo makes the keys absolute: a subtree of a larger tree can be searched with its true key range, which is how the recursion itself uses it. On valid inputs the path starts at the root and ends at . For an outside the tree’s range the path is the unsuccessful search path, ending at a leaf.
The search path holds exactly the proper ancestors of and itself. Below, “ancestor” includes the node itself.
Theorem (ancestors and common ancestors). Let have keys , and let be two of them. The search path to has keys, and the two search paths have exactly keys in common, the ancestors of the LCA.
/-- The search path includes exactly the proper ancestors and the key itself. -/theorem ancestor_count (t : Tree) (lo x : Nat) (hx : lo ≤ x ∧ x < lo + t.size) : (t.searchPath lo x).length = Tree.depth t (x - lo) + 1 := searchPath_length t lo x hx/-- The shared ancestors are the ancestors of the LCA, including the LCA. -/theorem common_ancestor_count (t : Tree) (lo x y : Nat) (hx : lo ≤ x ∧ x < lo + t.size) (hy : lo ≤ y ∧ y < lo + t.size) : ((t.searchPath lo x).toFinset ∩ (t.searchPath lo y).toFinset).card = lcaDepth t (x - lo) (y - lo) + 1 := common_ancestors_card t lo x y hx hyInside the statements, x - lo converts the absolute key back to the rank that Tree.depth and LazyFinger.lcaDepth expect.
Subtracting gives the distance as a sum of events, one for each key : counts once if it is an ancestor of exactly one endpoint, and not at all otherwise.
Theorem (distance as ancestor events). For keys of ,
where ranges over the keys of and means that is on the search path to .
/-- Distance is the count of ancestors belonging to exactly one endpoint. -/theorem distance_events (t : Tree) (lo x y : Nat) (hx : lo ≤ x ∧ x < lo + t.size) (hy : lo ≤ y ∧ y < lo + t.size) : (distance t (x - lo) (y - lo) : ℝ) = ∑ a ∈ Finset.Ico lo (lo + t.size), ((if a ∈ t.searchPath lo x then (1 : ℝ) else 0) + (if a ∈ t.searchPath lo y then (1 : ℝ) else 0) - 2 * (if a ∈ t.searchPath lo x ∧ a ∈ t.searchPath lo y then (1 : ℝ) else 0)) := distance_ancestor_sum t lo x y hx hyThe sum is in , with Iverson brackets written as if … then 1 else 0. Each term is or ; the subtraction is real only so that the statement can be averaged directly. Taking expectations over a random tree turns each bracket into the probability of an ancestor event, which is exactly how Theorem 1 is proved.
15.3 The lazy-finger cost
A lazy finger serves a request for , with the finger at , by walking from to and leaving the finger at . The cost of a sequence follows the finger:
/-- Lazy-finger cost from a specified initial key, including one per request. -/def costFrom (t : Tree) : Nat → List Nat → Nat | _, [] => 0 | p, x :: xs => 1 + distance t p x + costFrom t x xs/-- The first search starts at the root. Request charges ensure repeated keysstill cost one, consistently with the rest of the library. -/def cost : Tree → List Nat → Nat | .nil, xs => xs.length | .node l r, xs => costFrom (.node l r) l.size xscostFrom t p xs, written in the headline boxes, starts with the finger at the key p and charges each request , with . The unit is a charge per request, as in the static cost StaticTree.cost and the total cost of an online algorithm (Chapter 5). Without it, a repeated request would cost nothing.
cost t xs is the paper’s convention: the first search starts at the root, which in a node node l r is the rank l.size. On the empty tree there is no root, and cost returns xs.length, one unit per request. The empty tree has no keys, so this case only matters for totality.
In the paper’s notation, , and the root-finger cost is (Chapter 14).
Theorem (request charge). For every tree, start and sequence, costFrom is at least the number of requests.
theorem request_charge (t : Tree) (p : Nat) (xs : List Nat) : xs.length ≤ costFrom t p xs := length_le_costFrom t p xsThe start matters only once. Moving the initial finger from to the root changes the distance of the first move by at most the depth of , which is less than .
Theorem (initialization). For every tree on keys, every key of and every sequence of keys of , the lazy-finger costs from and from the root differ by at most , in both directions.
/-- Replacing a fixed tree's initial finger by its root costs at most `n` once. -/theorem initialization (t : Tree) (p : Nat) (xs : List Nat) (hp : p < t.size) (valid : ∀ x ∈ xs, x < t.size) : costFrom t p xs ≤ t.size + cost t xs ∧ cost t xs ≤ t.size + costFrom t p xs := initialization_bounds t p xs hp validLazy finger is never much worse than root finger in the same tree: the path from through the LCA to is no longer than the path from up to the root and down to .
Theorem (lazy finger versus root finger). For every tree and every sequence , the lazy-finger cost from the root is at most twice the root-finger cost: .
/-- The fixed-tree lazy-finger benchmark is no worse than twice root finger.This is the elementary comparison in §1.4 of arXiv:1304.6897, with requestcharges included and the initial finger at the root. -/theorem root_finger (t : Tree) (xs : List Nat) : cost t xs ≤ 2 * StaticTree.cost t xs := cost_le_twice_static t xsThe proof bounds each move by and sums: each depth appears at most twice, and the first search starts at the root, where . With the unit charges this gives . This is the comparison of §1.4 of the paper. The theorem has no validity hypothesis.
15.4 The optimal tree
The benchmark of the chapter is the best fixed tree for a given sequence.
/-- Best normalized lazy-finger cost among all shapes on `n` ordered keys.The attainment theorem supplies a minimizing shape; this definition alone isnot an executable dynamic-programming algorithm. -/noncomputable def optimalCost (n : Nat) (xs : List Nat) : Nat := sInf {k | ∃ t : Tree, t.size = n ∧ cost t xs = k}/-- Optimal fixed-tree cost with a specified initial finger. -/noncomputable def optimalCostFrom (n p : Nat) (xs : List Nat) : Nat := sInf {k | ∃ t : Tree, t.size = n ∧ costFrom t p xs = k}optimalCost n xs is the infimum of cost t xs over all shapes t with nodes, and optimalCostFrom n p xs the same with every tree started at the key p. Both are sInf of a set of natural numbers. Such a set has a least element whenever it is nonempty, and it is never empty here, since there are trees of every size. So both infima are minima, attained by actual trees.
Theorem (attainment). For every , every start and every sequence, some tree on keys has lazy-finger cost exactly optimalCost n xs, and some tree on keys has cost from exactly optimalCostFrom n p xs.
/-- The optimal benchmark is attained by an actual BST shape. This is anexistence result, not the paper's efficient construction algorithm. -/theorem optimal_attained (n : Nat) (xs : List Nat) : ∃ t : Tree, t.size = n ∧ cost t xs = optimalCost n xs := optimalCost_attained n xs/-- The minimum over fixed trees with a specified initial finger is attained. -/theorem optimal_from_attained (n p : Nat) (xs : List Nat) : ∃ t : Tree, t.size = n ∧ costFrom t p xs = optimalCostFrom n p xs := optimalCostFrom_attained n p xsThese are existence statements. They do not compute the optimal tree. The paper’s dynamic program, and its proof of optimality, are the subject of Chapter 27.
Theorem (the optimum is a lower bound). For every tree and every sequence, ; and the optimum is at least the number of requests.
theorem optimal_le (t : Tree) (xs : List Nat) : optimalCost t.size xs ≤ cost t xs := optimalCost_le t xstheorem optimal_request_charge (n : Nat) (xs : List Nat) : xs.length ≤ optimalCost n xs := length_le_optimalCost n xsCombined with the comparison with root finger, the optimal lazy-finger tree is at most twice as expensive as every root-finger tree, and in particular as the optimal one.
Theorem (optimal lazy finger versus root finger). For every tree and every sequence , .
/-- First inequality of the hierarchy, against every fixed root-finger tree. -/theorem optimal_root_finger (t : Tree) (xs : List Nat) : optimalCost t.size xs ≤ 2 * StaticTree.cost t xs := optimalCost_le_twice_static t xsThis is the first inequality of the paper’s Theorem 6, the hierarchy root finger, lazy finger, rotations. Chapter 16 proves the rest of the hierarchy, and the separations that make it strict.
15.5 Weighted dynamic finger
The other side of the characterization is a bound that mentions no tree at all. Assign each key a weight . The mass of a key range counts both endpoints:
/-- Inclusive interval mass; both endpoints contribute. -/noncomputable def mass (w : Nat → ℝ) (x y : Nat) : ℝ := ∑ k ∈ Finset.Icc (min x y) (max x y), w kmass w x y is . It does not depend on the order of and .
/-- The weighted dynamic-finger charge of Iacono and Langerman,arXiv:1810.01785. Bound statements require positive weights. -/noncomputable def charge (w : Nat → ℝ) (x y : Nat) : ℝ := 1 + Real.logb 2 (mass w x y / min (w x) (w y))The charge for moving from to is . It is small when the range between the two keys is light compared with the lighter endpoint. Think of as the number of “units of weight ” that separate the keys. With unit weights it is , the rank distance of the dynamic finger bound; with weights concentrated near a few keys, moves among those keys are cheap even when many light keys lie between them.
The charge is a real number with a real logarithm. When the weights are positive, the ratio is at least and the logarithm is nonnegative. The definition itself assumes nothing, and with zero or negative weights the value is a totalized artefact (Real.logb 2 of a nonpositive number is defined in Mathlib, but is not meaningful here). The theorems assume positivity where they need it.
Theorem (basic properties of the charge).
- With unit weights, the charge from to is , the dynamic finger charge of
Bounds.dynamicFingerCostFrom. - If , a repeated key costs exactly .
- The charge is symmetric in and .
- Multiplying all weights by the same positive constant does not change the charge.
- If the weights are positive on the range between and , the charge is at least .
/-- Unit weights specialize weighted dynamic finger to dynamic finger. Thisidentity alone does not assert a bound for GreedyASS. -/theorem unit_weights (x y : Nat) : charge (fun _ => 1) x y = 1 + Real.logb 2 ((max x y - min x y + 1 : Nat) : ℝ) := charge_unit x yBounds.WeightedFinger.Definitionstheorem repeated_key (w : Nat → ℝ) (x : Nat) (hx : 0 < w x) : charge w x x = 1 := charge_self w x hxBounds.WeightedFinger.Definitionstheorem symmetric (w : Nat → ℝ) (x y : Nat) : charge w x y = charge w y x := charge_symm w x yBounds.WeightedFinger.Definitionstheorem scale_invariant (w : Nat → ℝ) (c : ℝ) (hc : 0 < c) (x y : Nat) : charge (fun k => c * w k) x y = charge w x y := charge_scale w c hc x yBounds.WeightedFinger.Definitionstheorem request_charge (w : Nat → ℝ) (x y : Nat) (hw : ∀ k ∈ Finset.Icc (min x y) (max x y), 0 < w k) : 1 ≤ charge w x y := charge_ge_one w x y hwBounds.WeightedFinger.DefinitionsScale invariance means that only the relative weights matter; the weights need not sum to . The lower bound is the request charge again: like the lazy-finger cost, the weighted charge pays one unit for every request, including repeats.
The bound for a sequence adds the charges of consecutive requests, from an explicit start:
/-- Charges for consecutive requests, with the preceding request explicit. -/noncomputable def costFrom (w : Nat → ℝ) : Nat → List Nat → ℝ | _, [] => 0 | p, x :: xs => charge w p x + costFrom w x xscostFrom w p xs is with , the weighted dynamic finger bound of Iacono and Langerman. The optimal choice of weights gives a function of the sequence alone:
/-- Infimum over positive weights on the key universe. No attainment of thisreal-valued infimum is assumed. The comparison theorems require valid requestsand a valid initial finger in this universe. -/noncomputable def optimalCostFrom (n p : Nat) (xs : List Nat) : ℝ := sInf {c | ∃ w : Nat → ℝ, (∀ k < n, 0 < w k) ∧ costFrom w p xs = c}optimalCostFrom n p xs is the infimum of costFrom w p xs over all weightings that are positive on the keys . Values of outside that range are unconstrained, and on valid requests the charges never read them.
- An infimum, not a minimum. The weights range over a continuum, and the library does not claim that a best weighting exists. The paper writes .
- Valid inputs. In Lean,
sInfof a set of reals that is not bounded below is . The library proves the lower bound for the set when the start and the requests are keys, so every theorem aboutoptimalCostFromassumes and that every request is less than . - A start key. The weighted bound always starts from a key . Unlike a tree, a weighting has no root to start from.
Under those hypotheses the optimum behaves as expected.
Theorem (the weight optimum). Let and let every request be less than . Then , and for every weighting positive on the keys.
/-- The optimized weighted benchmark still pays for every request. -/theorem optimal_request_charge (n p : Nat) (xs : List Nat) (hp : p < n) (valid : ∀ x ∈ xs, x < n) : (xs.length : ℝ) ≤ optimalCostFrom n p xs := length_le_optimalCostFrom n p xs hp validBounds.WeightedFinger.Definitions/-- Every positive weighting is an upper bound on the weight infimum. -/theorem optimal_le (w : Nat → ℝ) (n p : Nat) (xs : List Nat) (hw : ∀ k < n, 0 < w k) (hp : p < n) (valid : ∀ x ∈ xs, x < n) : optimalCostFrom n p xs ≤ costFrom w p xs := optimalCostFrom_le w n p xs hw hp validBounds.WeightedFinger.Definitions15.6 A random tree for given weights
The first step of the characterization builds a tree from weights. The tree is random: it is the treap of Seidel and Aragon, whose priorities are drawn according to the weights. The paper describes it as “recursively pick the root using the normalized weights of all nodes as probabilities”. The library draws a whole random order of the keys at once, by weighted sampling without replacement, and builds the treap in which earlier keys sit higher. The expectation over this sampling process is Random.average, defined in Chapter 32: it chooses the first key of the order with probability proportional to its weight, removes it, and averages recursively over the order of the rest. It is a finite sum, not a measure-theoretic expectation.
The key fact about the treap is the probability of an ancestor event: a key is an ancestor of exactly when comes first, among the keys between and , in the order, and under weighted sampling that happens with probability . Averaging the ancestor-event formula of Section 15.2 gives the expected distance exactly.
Theorem (expected distance in a weighted treap). Let be positive on the keys . There is an assignment of a tree on nodes to every order, such that for all keys in the range,
where ranges over the keys and the expectation is over the weighted random order.
/-- Exact expected distance for one family of weighted random treaps, uniformlyfor all valid pairs. The logarithmic consequence is stated below. -/theorem expected_distance (w : Nat → ℝ) (n lo : Nat) (hw : ∀ k ∈ Finset.Ico lo (lo + n), 0 < w k) : ∃ T : List Nat → Tree, (∀ xs, (T xs).size = n) ∧ ∀ x y, lo ≤ x → x < lo + n → lo ≤ y → y < lo + n → average w (Finset.Ico lo (lo + n)) (fun xs => (distance (T xs) (x - lo) (y - lo) : ℝ)) = ∑ a ∈ Finset.Ico lo (lo + n), (w a / (∑ k ∈ Finset.Icc (min a x) (max a x), w k) + w a / (∑ k ∈ Finset.Icc (min a y) (max a y), w k) - 2 * (w a / (∑ k ∈ Finset.Icc (min a (min x y)) (max a (max x y)), w k))) := exists_expected_distance w n lo hwThe tree holds the ranks and stands for the keys ; hence x - lo in the statement. The third term is the probability that is a common ancestor: it must come first in the smallest range containing , and . The family is existential in the statement. In the proof it is the treap of the order, chosen through the existence of heap-ordered trees in Chapter 32.
Bounding the sum by logarithms gives Theorem 1. Split the keys into those below, between and above and . For a key outside the range, the term is a difference of two probabilities, such as for , and these differences sum to a logarithmic amount that does not depend on the weight outside the range. For a key inside the range, the terms are like , and the inequality compares their sum with the growth of as moves from to . The library obtains for the expected distance, then replaces by and adds the request charge.
Theorem 1 (a random tree realizes the weights). Let be positive on . There is an assignment of a tree on nodes to every order such that, for all keys , .
/-- The same random family satisfies the weighted dynamic-finger bound forall pairs. This counts one request plus movement and uses base-two logarithms. -/theorem weighted_charge (w : Nat → ℝ) (n : Nat) (hw : ∀ k < n, 0 < w k) : ∃ T : List Nat → Tree, (∀ xs, (T xs).size = n) ∧ ∀ x y, x < n → y < n → average w (Finset.range n) (fun xs => 1 + (distance (T xs) x y : ℝ)) ≤ 4 * WeightedFinger.charge w x y := exists_expected_charge_bound w n hwThe quantifiers carry the content. The family is chosen after and and before and , so one random tree is good for all pairs at once, and, by linearity of expectation, for every sequence. The paper states the bound as without the request charge; the library’s form, with the unit on both sides, has the explicit constant .
expected_distance and weighted_charge are proved from the same treap family, but each statement quantifies its own family existentially. As stated, they do not assert that one family satisfies both.
15.7 From weights to a tree and back
Theorem 1 is an average over trees. For a fixed sequence, some single tree is at least as good as the average: this is the probabilistic method, and it is Corollary 2 of the paper.
Corollary 2 (weights give a tree). Let be positive on , let , and let be a sequence of keys less than . There is a tree on keys with .
/-- Weights-to-tree direction of the lazy-finger characterization, with anexplicit initial finger and normalized request charges. A single fixed treeserves the entire sequence; its choice may depend on the weights and sequence. -/theorem tree_for_weights (w : Nat → ℝ) (n p : Nat) (xs : List Nat) (hw : ∀ k < n, 0 < w k) (hp : p < n) (valid : ∀ x ∈ xs, x < n) : ∃ t : Tree, t.size = n ∧ (costFrom t p xs : ℝ) ≤ 4 * WeightedFinger.costFrom w p xs := exists_tree_for_weights w n p xs hw hp validThe proof sums Theorem 1 over the consecutive pairs of , so that the expected cost of is at most , and then picks an order whose cost is at most the average. The tree therefore depends on the sequence as well as on the weights. It is fixed once chosen: it serves all of without changing.
The converse direction represents a given tree by weights. The proof gives a key at depth the weight , the same weights as in the proof of the entropy bound of Chapter 14. (The paper uses ; the constant factor cancels in every charge, by scale invariance.)
- Lower bound on the charge. The range between and contains their LCA, whose weight is for its depth. The lighter endpoint has weight . So the mass ratio is at least , and its logarithm at least .
- Upper bound on the charge. The range between and lies inside the subtree of their LCA. In that subtree the weights decrease by a factor of per level while the number of nodes per level at most doubles, so the total is at most a constant times the LCA’s weight. Dividing by the lighter endpoint’s weight, the logarithm is at most a constant plus .
Lemma 3 (trees give weights). For every tree there is a weighting , positive everywhere, such that for all keys of , . Consequently, for every key of and every sequence of keys of , .
/-- Both pairwise and sequence comparisons use the same positive weights. -/theorem tree_weights_two_sided (t : Tree) : ∃ w : Nat → ℝ, (∀ x, 0 < w x) ∧ (∀ x y, x < t.size → y < t.size → 1 + (distance t x y : ℝ) ≤ WeightedFinger.charge w x y ∧ WeightedFinger.charge w x y ≤ 3 + 2 * (distance t x y : ℝ)) ∧ (∀ p xs, p < t.size → (∀ x ∈ xs, x < t.size) → (costFrom t p xs : ℝ) ≤ WeightedFinger.costFrom w p xs ∧ WeightedFinger.costFrom w p xs ≤ 3 * (costFrom t p xs : ℝ)) := exists_two_sided_weights tThe weighting depends on only: one weighting works for every pair, every start and every sequence. The sequence bounds follow by summing the pairwise bounds, using .
Corollary 4 (the reverse comparison). For every tree there is a weighting , positive everywhere, with for all keys of , and for every key and every sequence of keys of .
/-- Tree-to-weights direction of the characterization in §3 ofarXiv:1304.6897, with explicit constants and normalized request charges.One positive weighting works for every valid pair and every valid sequenceon this tree. The converse weights-to-tree direction is separate. -/theorem tree_weights (t : Tree) : ∃ w : Nat → ℝ, (∀ x, 0 < w x) ∧ (∀ x y, x < t.size → y < t.size → WeightedFinger.charge w x y ≤ 3 + 2 * (distance t x y : ℝ)) ∧ (∀ p xs, p < t.size → (∀ x ∈ xs, x < t.size) → WeightedFinger.costFrom w p xs ≤ 3 * (costFrom t p xs : ℝ)) := exists_weights_for_tree tCorollary 4 is the upper half of Lemma 3, and it is the half that the characterization uses: every tree’s cost is at least a third of the weighted bound of its own weights, hence at least a third of the optimal weighted bound.
The paper’s Lemma 3 states the lower bound on the charge, , and its proof shows . Its Corollary 4, , needs the opposite comparison, for the same weights. The library proves both directions in tree_weights_two_sided. The upper bound uses the total weight of the LCA’s subtree, as sketched above, not only the LCA’s own weight.
15.8 The characterization
The two directions combine as in the paper’s proof of Theorem 5. For the upper bound, take any weighting : Corollary 2 gives a tree of cost at most , so the optimal tree costs at most that much, and taking the infimum over gives . For the lower bound, take an optimal tree, which exists by attainment: Corollary 4 gives a weighting whose weighted cost is at most , and the infimum over weights is at most that.
Theorem 5 (characterization from a common start). Let and let be a sequence of keys less than . Then and .
/-- Weight/tree characterization with the same specified initial key on bothsides. The tree minimum is attained; the weight benchmark is an infimum. -/theorem characterization_from (n p : Nat) (xs : List Nat) (hp : p < n) (valid : ∀ x ∈ xs, x < n) : WeightedFinger.optimalCostFrom n p xs ≤ 3 * (optimalCostFrom n p xs : ℝ) ∧ (optimalCostFrom n p xs : ℝ) ≤ 4 * WeightedFinger.optimalCostFrom n p xs := optimal_from_characterization n p xs hp validThis is the cleanest form: both benchmarks start from the same key, and there is no additive term. The paper’s tree cost starts at the root of each tree, which has no counterpart for weights. The initialization theorem of Section 15.3 bounds the difference by , and gives the root-start form.
Theorem 5 (root start). Let and let be a sequence of keys less than . Then and .
/-- Root-start characterization with explicit initialization terms. -/theorem characterization_root (n p : Nat) (xs : List Nat) (hp : p < n) (valid : ∀ x ∈ xs, x < n) : WeightedFinger.optimalCostFrom n p xs ≤ 3 * ((optimalCost n xs : ℝ) + n) ∧ (optimalCost n xs : ℝ) ≤ n + 4 * WeightedFinger.optimalCostFrom n p xs := optimal_root_characterization n p xs hp validOn the weighted side, is any key: the comparison holds for every choice of start for the weights simultaneously. Adding to both benchmarks makes the two inequalities symmetric:
Theorem 5 (with startup). Under the same hypotheses, and .
/-- Adding the startup allowance `n` makes the benchmarks factor-four equivalent. -/theorem characterization (n p : Nat) (xs : List Nat) (hp : p < n) (valid : ∀ x ∈ xs, x < n) : (optimalCost n xs : ℝ) + n ≤ 4 * (WeightedFinger.optimalCostFrom n p xs + n) ∧ WeightedFinger.optimalCostFrom n p xs + n ≤ 4 * ((optimalCost n xs : ℝ) + n) := characterization_with_startup n p xs hp validOn long sequences the additive term disappears, because both benchmarks charge at least one unit per request, so each is at least .
Theorem 5 (long sequences). If moreover , then and .
/-- When `m ≥ n`, no separate additive startup term is needed. -/theorem characterization_long_sequence (n p : Nat) (xs : List Nat) (hp : p < n) (valid : ∀ x ∈ xs, x < n) (long : n ≤ xs.length) : WeightedFinger.optimalCostFrom n p xs ≤ 6 * (optimalCost n xs : ℝ) ∧ (optimalCost n xs : ℝ) ≤ 5 * WeightedFinger.optimalCostFrom n p xs := characterization_long n p xs hp valid longThe paper states Theorem 5 as , with the root of . The library’s statements differ in four explicit ways.
- Unit charges. Both sides charge one unit per request. The paper’s sums have none.
- The start. The weighted side starts from an explicit key . The tree side starts either from the same key (
characterization_from) or from the root, at the price of an additive (characterization_root,characterization) or of the assumption (characterization_long_sequence). - Infimum. The minimum over weights is an infimum; the minimum over trees is attained.
- Constants. All constants are explicit, and is base two on both sides.
The characterization is used in two places. Chapter 16 derives from it that the optimal lazy-finger tree satisfies the static finger, static optimality and dynamic finger bounds simultaneously, and Section 25.3 proves that GreedyASS is competitive with both benchmarks at once.
15.9 Distance as boundary crossings
The last section gives a third description of the cost, which is not needed for the characterization. Each edge of a tree connects a subtree to its parent, and each subtree holds a contiguous range of keys. A move from to uses that edge exactly when one of is in the subtree’s range and the other is not. So the lazy-finger cost of a sequence is a sum, over the subtrees, of the number of times the sequence crosses the boundary of the subtree’s key range. The number of crossings of a range depends only on the range and the sequence, not on the tree. This turns the search for an optimal tree into an optimization over nested ranges, which is the dynamic program of Chapter 27.
/-- Whether a transition crosses the boundary of the half-open rank interval.This is exactly the use of the edge connecting that subtree to its parent. -/def cut (lo hi x y : Nat) : Nat := if (lo ≤ x ∧ x < hi) ↔ (lo ≤ y ∧ y < hi) then 0 else 1/-- Sum a boundary toll over the intervals of all nonempty subtrees, includingthis tree itself. Its incoming edge is included; set the full-universe toll tozero when both endpoints are inside the tree. -/def intervalCost (w : Nat → Nat → Nat) : Tree → Nat → Nat | .nil, _ => 0 | .node l r, lo => w lo (lo + (.node l r : Tree).size) + intervalCost w l lo + intervalCost w r (lo + l.size + 1)/-- Movement within a subtree, including its incoming edge. Endpoints may lieoutside the subtree, which is essential for decomposing a global sequence. -/def edgeMovement (t : Tree) (lo x y : Nat) : Nat := intervalCost (fun a b => cut a b x y) t lo/-- Boundary crossings of a sequence with an explicit initial key. -/def crossings (lo hi : Nat) : Nat → List Nat → Nat | _, [] => 0 | p, x :: xs => cut lo hi p x + crossings lo hi x xscut lo hi x yis if exactly one of lies in the half-open range , and otherwise.intervalCost w t losums a tollw lo hiover the key ranges of all nonempty subtrees oft, whose keys start atlo, includingtitself. The toll of the whole tree’s range stands for the edge from the tree to its parent, which a subtree has and the whole tree does not.edgeMovement t lo x yuses the tollcut: it counts the subtrees separating from , that is, the edges of the path between them, plus the incoming edge if only one endpoint is inside. The endpoints may lie outsidet, which is what lets the movement of a global sequence be split among subtrees.crossings lo hi p xscounts the consecutive pairs of the sequence, from , that cross the boundary of .
The basic facts are the three cases of a single move.
Theorem (one move, by subtrees). Let have keys . If neither nor is a key of , the move uses no edge of and does not enter it. If is a key of and is not, it uses the path from to the root of and the edge above it, edges. If both are keys of , it uses exactly edges, and the whole tree’s own range contributes nothing.
/-- A transition with both endpoints outside a subtree uses no internal edges. -/theorem outside (t : Tree) (lo x y : Nat) (hx : ¬ (lo ≤ x ∧ x < lo + t.size)) (hy : ¬ (lo ≤ y ∧ y < lo + t.size)) : edgeMovement t lo x y = 0 := edgeMovement_outside t lo x y hx hyModels.Rotation, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Bounds.LazyFinger.Edges.Definitions/-- Entering or leaving uses the endpoint's root path and one incoming edge. -/theorem entering (t : Tree) (lo x y : Nat) (hx : lo ≤ x ∧ x < lo + t.size) (hy : ¬ (lo ≤ y ∧ y < lo + t.size)) : edgeMovement t lo x y = Tree.depth t (x - lo) + 1 := edgeMovement_enter t lo x y hx hyModels.Rotation, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Bounds.LazyFinger.Edges.Definitions/-- Summing subtree-boundary crossings gives the exact distance between keys. -/theorem distance (t : Tree) (lo x y : Nat) (hx : lo ≤ x ∧ x < lo + t.size) (hy : lo ≤ y ∧ y < lo + t.size) : edgeMovement t lo x y = LazyFinger.distance t (x - lo) (y - lo) := edgeMovement_inside t lo x y hx hyModels.Rotation, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Bounds.LazyFinger.Edges.DefinitionsSumming over the moves of a sequence exchanges the two sums: the cost is the number of requests plus, for each subtree, the number of times the sequence crosses its range.
Theorem (cost as crossings). For every tree , every key and every sequence of keys of , , where ranges over the key ranges of the nonempty subtrees of , including ’s own.
/-- Sequence cost is the request count plus the sum of all boundary crossings. -/theorem sequence (t : Tree) (p : Nat) (xs : List Nat) (hp : p < t.size) (valid : ∀ x ∈ xs, x < t.size) : costFrom t p xs = xs.length + intervalCost (fun a b => crossings a b p xs) t 0 := costFrom_eq_crossings t p xs hp validModels.Rotation, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Bounds.LazyFinger.Edges.DefinitionsThe root start fits the same form. Start the sequence instead at the key , just outside the tree: the first move enters the tree through an imaginary edge above its root, so it costs exactly one more than starting at the root, and nothing else changes.
Theorem (root start as crossings). For every tree on keys and every sequence of its keys, .
/-- The external initial key adds exactly one edge on a nonempty sequence,independently of the shape's root. This converts root initialization to a fixedboundary objective for interval optimization. -/theorem initialization (t : Tree) (xs : List Nat) (valid : ∀ x ∈ xs, x < t.size) : cost t xs + (if xs = [] then 0 else 1) = xs.length + intervalCost (fun a b => crossings a b t.size xs) t 0 := cost_eq_crossings t xs validModels.Rotation, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Bounds.LazyFinger.Edges.DefinitionsThe correction does not depend on the shape, so a tree that minimizes the right side also minimizes the root-start cost. This is how Chapter 27 computes LazyFinger.optimalCost with the same dynamic program as LazyFinger.optimalCostFrom.
A rotation changes exactly one subtree: the two nodes it moves swap which of them is the parent, so one subtree range disappears and one new range appears, and all other subtree ranges stay the same. Hence a rotation changes the sum by at most one toll.
Theorem (rotation sensitivity). Let every toll be at most . If rotates to , then the interval cost of is at most that of plus . In particular, if every range is crossed at most times by a sequence from , then one rotation increases by at most .
/-- One rotation replaces one proper-subtree interval, so bounded boundarytolls have bounded sensitivity to any single rotation. -/theorem rotation (w : Nat → Nat → Nat) (C : Nat) (bounded : ∀ lo hi, w lo hi ≤ C) {s t : Tree} (rotation : Rotate s t) (lo : Nat) : intervalCost w t lo ≤ intervalCost w s lo + C := intervalCost_rotate_le w C bounded rotation loModels.Rotation, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Bounds.LazyFinger.Edges.Definitions/-- The same stability applies to normalized sequence cost. -/theorem sequence_rotation {s t : Tree} (rotation : Rotate s t) (p : Nat) (xs : List Nat) (initial : p < s.size) (valid : ∀ x ∈ xs, x < s.size) (C : Nat) (bounded : ∀ lo hi, crossings lo hi p xs ≤ C) : costFrom t p xs ≤ costFrom s p xs + C := costFrom_rotate_le rotation p xs initial valid C boundedModels.Rotation, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Bounds.LazyFinger.Edges.DefinitionsRotate is a single rotation anywhere in the tree (Chapter 2). These two bounds say how sensitive the lazy-finger cost is to the shape: trees one rotation apart cost almost the same on a sequence that crosses every range only a few times. No other theorem of the reading interface uses them.
The crossings of a range depend on the sequence only through the number of times each ordered pair of keys occurs consecutively. The library makes this explicit:
/-- Directed adjacent-pair frequency, including the supplied initial key. -/def frequency : Nat → List Nat → Nat → Nat → Nat | _, [], _, _ => 0 | p, x :: xs, a, b => (if a = p ∧ b = x then 1 else 0) + frequency x xs a b/-- Boundary traffic computed from a finite directed frequency matrix. -/def frequencyToll (n : Nat) (f : Nat → Nat → Nat) (lo hi : Nat) : Nat := ∑ a ∈ Finset.range n, ∑ b ∈ Finset.range n, f a b * cut lo hi a bfrequency p xs a b is the paper’s : the number of indices with and , counting the initial pair . frequencyToll n f lo hi sums over the pairs of keys that cross the boundary of . Applied to the pair frequencies of a sequence of valid keys, it equals crossings lo hi p xs; the library proves this as the internal lemma frequencyToll_eq_crossings. So the optimal tree is a function of the table of pair frequencies, as the paper observes. Chapter 27 computes the tolls from that table by prefix sums, and Chapter 18 uses the same table for the conditional entropy.