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

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 xx costs the depth of xx. Its optimum is well understood: the best static tree serves a sequence in time proportional to mm 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 xx to yy, the finger climbs from xx to their lowest common ancestor and descends to yy. 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 0,1,…,n−1,0,1,…0, 1, \dots, n-1, 0, 1, \dots of length m≥nm \ge n costs O(m)O(m) with a lazy finger in every tree, but Ω(mlog⁡n)\Omega(m \log n) 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 kk a positive weight wkw_k, and charge a move from xx to yy

1+log⁡2∑k=min⁡(x,y)max⁡(x,y)wkmin⁡(wx,wy).1 + \log_2 \frac{\sum_{k = \min(x,y)}^{\max(x,y)} w_k}{\min(w_x, w_y)}.

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).

Key result · Bose et al. 2016
The optimal lazy-finger tree costs the best weighted dynamic finger bound, up to constant factors

Let X=x1,…,xmX = x_1, \dots, x_m be requests to the keys {0,…,n−1}\{0, \dots, n-1\}, and let p<np < n be a starting key. Write dT(x,y)d_T(x, y) for the number of edges between xx and yy in a tree TT, and W(x,y)=∑k=min⁡(x,y)max⁡(x,y)wkW(x,y) = \sum_{k=\min(x,y)}^{\max(x,y)} w_k. Define, with x0=px_0 = p,

LFp(X)=min⁡T∑i=1m(1+dT(xi−1,xi)),WDFp(X)=inf⁡w>0∑i=1m(1+log⁡2W(xi−1,xi)min⁡(wxi−1,wxi)),\mathrm{LF}_p(X) = \min_{T} \sum_{i=1}^m \bigl(1 + d_T(x_{i-1}, x_i)\bigr), \qquad \mathrm{WDF}_p(X) = \inf_{w > 0} \sum_{i=1}^m \Bigl(1 + \log_2 \frac{W(x_{i-1}, x_i)}{\min(w_{x_{i-1}}, w_{x_i})}\Bigr),

the minimum over all binary search trees on the nn keys, and the infimum over all weightings that are positive on the nn keys. Let LF(X)\mathrm{LF}(X) be defined like LFp(X)\mathrm{LF}_p(X), except that the first search starts at the root of TT. Then

WDFp(X)≤3 LFp(X),LFp(X)≤4 WDFp(X),\mathrm{WDF}_p(X) \le 3\,\mathrm{LF}_p(X), \qquad \mathrm{LF}_p(X) \le 4\,\mathrm{WDF}_p(X),

and, for the root start, with an additive nn for the initial position,

LF(X)+n≤4 (WDFp(X)+n),WDFp(X)+n≤4 (LF(X)+n).\mathrm{LF}(X) + n \le 4\,\bigl(\mathrm{WDF}_p(X) + n\bigr), \qquad \mathrm{WDF}_p(X) + n \le 4\,\bigl(\mathrm{LF}(X) + n\bigr).

If m≥nm \ge n, the additive term is not needed: WDFp(X)≤6 LF(X)\mathrm{WDF}_p(X) \le 6\,\mathrm{LF}(X) and LF(X)≤5 WDFp(X)\mathrm{LF}(X) \le 5\,\mathrm{WDF}_p(X).

Both costs charge one unit per request, and the minimum over trees is attained. In Lean, LFp\mathrm{LF}_p is LazyFinger.optimalCostFrom, LF\mathrm{LF} is LazyFinger.optimalCost, and WDFp\mathrm{WDF}_p is WeightedFinger.optimalCostFrom.

The Lean statements
theoremLazyFinger.Results.characterization_frompropext · Classical.choice · Quot.soundBounds/LazyFinger/Abstract.lean:96
/-- 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
theoremLazyFinger.Results.characterizationpropext · Classical.choice · Quot.soundBounds/LazyFinger/Abstract.lean:117
/-- 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
theoremLazyFinger.Results.characterization_long_sequencepropext · Classical.choice · Quot.soundBounds/LazyFinger/Abstract.lean:124
/-- 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 long
12 definitions in 2 chapters · reading list
Main result · Bose et al. 2016
Weights give a tree, and every tree is represented by weights

With the notation of the previous box, write LFp(T,X)=∑i(1+dT(xi−1,xi))\mathrm{LF}_p(T, X) = \sum_i (1 + d_T(x_{i-1}, x_i)) for the lazy-finger cost of one tree TT from x0=px_0 = p, cw(x,y)=1+log⁡2(W(x,y)/min⁡(wx,wy))c_w(x, y) = 1 + \log_2\bigl(W(x,y) / \min(w_x, w_y)\bigr) for the weighted charge, and WDFp(w,X)=∑icw(xi−1,xi)\mathrm{WDF}_p(w, X) = \sum_i c_w(x_{i-1}, x_i).

  • Weights give a tree (Corollary 2). For every weighting ww positive on {0,…,n−1}\{0, \dots, n-1\}, every p<np < n and every sequence XX of keys less than nn, there is a tree TT on the nn keys with LFp(T,X)≤4 WDFp(w,X)\mathrm{LF}_p(T, X) \le 4\,\mathrm{WDF}_p(w, X). The tree may depend on ww and on XX.
  • Trees give weights (Lemma 3). For every tree TT there is one weighting ww, positive everywhere, such that 1+dT(x,y)≤cw(x,y)≤3+2 dT(x,y)1 + d_T(x, y) \le c_w(x, y) \le 3 + 2\,d_T(x, y) for all keys x,yx, y of TT, and hence, for every valid start pp and sequence XX, LFp(T,X)≤WDFp(w,X)≤3 LFp(T,X)\mathrm{LF}_p(T, X) \le \mathrm{WDF}_p(w, X) \le 3\,\mathrm{LF}_p(T, X).
  • The reverse comparison (Corollary 4) is the upper half: cw(x,y)≤3+2 dT(x,y)c_w(x,y) \le 3 + 2\,d_T(x,y) and WDFp(w,X)≤3 LFp(T,X)\mathrm{WDF}_p(w, X) \le 3\,\mathrm{LF}_p(T, X).

In Lean, LFp(T,X)\mathrm{LF}_p(T, X) is LazyFinger.costFrom, cwc_w is WeightedFinger.charge and WDFp(w,X)\mathrm{WDF}_p(w, X) is WeightedFinger.costFrom.

The Lean statements
theoremLazyFinger.Results.tree_for_weightspropext · Classical.choice · Quot.soundBounds/LazyFinger/Abstract.lean:82
/-- 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
theoremLazyFinger.Results.tree_weights_two_sidedpropext · Classical.choice · Quot.soundBounds/LazyFinger/Abstract.lean:131
/-- 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
theoremLazyFinger.Results.tree_weightspropext · Classical.choice · Quot.soundBounds/LazyFinger/Abstract.lean:49
/-- 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 t
8 definitions in 2 chapters · reading list
Main result · Bose et al. 2016
A random tree realizes the weighted dynamic finger bound for every pair

Let ww be positive on {0,…,n−1}\{0, \dots, n-1\}. 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 TσT_\sigma on the nn keys to every order σ\sigma such that, for all keys x,y<nx, y < n,

Eσ[ 1+dTσ(x,y) ]  ≤  4 (1+log⁡2W(x,y)min⁡(wx,wy)).\mathbb E_\sigma\bigl[\,1 + d_{T_\sigma}(x, y)\,\bigr] \;\le\; 4\,\Bigl(1 + \log_2 \frac{W(x,y)}{\min(w_x, w_y)}\Bigr).

The assignment depends on ww and nn 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, TσT_\sigma is the treap whose priority order is σ\sigma. In Lean, the expectation is Random.average and the right side is 44 times WeightedFinger.charge.

The Lean statement
theoremLazyFinger.Random.Results.weighted_chargepropext · Classical.choice · Quot.soundBounds/LazyFinger/Random/Abstract.lean:22
/-- 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 hw
7 definitions in 3 chapters · reading list

The 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 nn nodes holds the keys 0,…,n−10, \dots, n-1 in inorder, and the root of node l r is the rank l.size. The paper writes r(T,i,j)r(T, i, j) for the time to move a pointer from ii to jj; the library calls it the distance.

defLazyFinger.distanceno axiomsBounds/LazyFinger/Definitions/Abstract.lean:9
/-- 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) y

If 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 xx to the root and down to yy, so its length is the sum of the two depths. Depth is Tree.depth (Chapter 1), with the root at depth 00, so the distance from a key to itself is 00 and the distance between a parent and a child is 11.

Reading the Lean
  • 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, distance still 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:

defLazyFinger.lcaDepthno axiomsBounds/LazyFinger/Definitions/Abstract.lean:20
/-- 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 0

The definitions fit together as in the paper’s formula r(T,i,j)=dT(i)+dT(j)−2 dT(LCAT(i,j))r(T, i, j) = d_T(i) + d_T(j) - 2\,d_T(\mathrm{LCA}_T(i,j)).

Theorem (LCA identity). For every tree TT and all ranks x,yx, y,   dT(x,y)+2 lcaDepthT(x,y)=depthT(x)+depthT(y)\;d_T(x, y) + 2\,\mathrm{lcaDepth}_T(x, y) = \mathrm{depth}_T(x) + \mathrm{depth}_T(y).

theoremLazyFinger.Results.lca_identitypropext · Quot.soundBounds/LazyFinger/Abstract.lean:24
/-- 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 y

The 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 TT: dT(x,y)=dT(y,x)d_T(x, y) = d_T(y, x) for all x,yx, y; dT(x,x)=0d_T(x, x) = 0 for every key xx; and for keys x,yx, y, dT(x,y)=0d_T(x, y) = 0 exactly when x=yx = y.

theoremLazyFinger.Results.symmetricpropext · Quot.soundBounds/LazyFinger/Abstract.lean:15
theorem symmetric (t : Tree) (x y : Nat) : distance t x y = distance t y x :=  distance_symm t x y
theoremLazyFinger.Results.repeated_keypropext · Classical.choice · Quot.soundBounds/LazyFinger/Abstract.lean:18
theorem repeated_key (t : Tree) (x : Nat) (hx : x < t.size) :    distance t x x = 0 := distance_self t x hx
theoremLazyFinger.Results.zero_distancepropext · Classical.choice · Quot.soundBounds/LazyFinger/Abstract.lean:30
/-- 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 hy

The triangle inequality also holds, since dTd_T 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 xx and yy 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 xx by the search path to xx:

defTree.searchPathno axiomsModels/Rotation/Search/Abstract.lean:8
/-- 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) x

searchPath t lo x lists the keys visited by an ordinary root-to-leaf search for xx, in a tree whose inorder ranks start at lo, so that its root is lo + l.size. The search compares xx 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 xx. For an xx 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 xx and xx itself. Below, “ancestor” includes the node itself.

Theorem (ancestors and common ancestors). Let TT have keys lo,…,lo+n−1lo, \dots, lo + n - 1, and let x,yx, y be two of them. The search path to xx has depth(x)+1\mathrm{depth}(x) + 1 keys, and the two search paths have exactly lcaDepth(x,y)+1\mathrm{lcaDepth}(x, y) + 1 keys in common, the ancestors of the LCA.

theoremLazyFinger.Results.ancestor_countpropext · Classical.choice · Quot.soundBounds/LazyFinger/Abstract.lean:61
/-- 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
theoremLazyFinger.Results.common_ancestor_countpropext · Classical.choice · Quot.soundBounds/LazyFinger/Abstract.lean:66
/-- 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 hy

Inside 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 aa: aa counts once if it is an ancestor of exactly one endpoint, and not at all otherwise.

Theorem (distance as ancestor events). For keys x,yx, y of TT,

dT(x,y)  =  ∑a([a⪯x]+[a⪯y]−2 [a⪯x and a⪯y]),d_T(x, y) \;=\; \sum_{a} \Bigl([a \preceq x] + [a \preceq y] - 2\,[a \preceq x \text{ and } a \preceq y]\Bigr),

where aa ranges over the keys of TT and a⪯xa \preceq x means that aa is on the search path to xx.

theoremLazyFinger.Results.distance_eventspropext · Classical.choice · Quot.soundBounds/LazyFinger/Abstract.lean:72
/-- 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 hy

The sum is in R\mathbb R, with Iverson brackets written as if … then 1 else 0. Each term is 00 or 11; 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 xx, with the finger at pp, by walking from pp to xx and leaving the finger at xx. The cost of a sequence follows the finger:

defLazyFinger.costFromno axiomsBounds/LazyFinger/Definitions/Abstract.lean:29
/-- 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
defLazyFinger.costno axiomsBounds/LazyFinger/Definitions/Abstract.lean:34
/-- 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 xs

costFrom t p xs, written LFp(T,X)\mathrm{LF}_p(T, X) in the headline boxes, starts with the finger at the key p and charges each request 1+dT(xi−1,xi)1 + d_T(x_{i-1}, x_i), with x0=px_0 = p. 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, cost(T,X)=m+Rℓ(T,X)\mathtt{cost}(T, X) = m + R_\ell(T, X), and the root-finger cost is StaticTree.cost(T,X)=m+Rr(T,X)\mathtt{StaticTree.cost}(T, X) = m + R_r(T, X) (Chapter 14).

Theorem (request charge). For every tree, start and sequence, costFrom is at least the number of requests.

The start matters only once. Moving the initial finger from pp to the root changes the distance of the first move by at most the depth of pp, which is less than nn.

Theorem (initialization). For every tree TT on nn keys, every key pp of TT and every sequence of keys of TT, the lazy-finger costs from pp and from the root differ by at most nn, in both directions.

theoremLazyFinger.Results.initializationpropext · Classical.choice · Quot.soundBounds/LazyFinger/Abstract.lean:104
/-- 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 valid

Lazy finger is never much worse than root finger in the same tree: the path from xi−1x_{i-1} through the LCA to xix_i is no longer than the path from xi−1x_{i-1} up to the root and down to xix_i.

Theorem (lazy finger versus root finger). For every tree TT and every sequence XX, the lazy-finger cost from the root is at most twice the root-finger cost: cost(T,X)≤2 StaticTree.cost(T,X)\mathtt{cost}(T, X) \le 2\,\mathtt{StaticTree.cost}(T, X).

theoremLazyFinger.Results.root_fingerpropext · Quot.soundBounds/LazyFinger/Abstract.lean:9
/-- 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 xs

The proof bounds each move by depth(xi−1)+depth(xi)\mathrm{depth}(x_{i-1}) + \mathrm{depth}(x_i) and sums: each depth appears at most twice, and the first search starts at the root, where depth(x0)=0\mathrm{depth}(x_0) = 0. With the unit charges this gives m+2∑idepth(xi)≤2 (m+∑idepth(xi))m + 2\sum_i \mathrm{depth}(x_i) \le 2\,(m + \sum_i \mathrm{depth}(x_i)). 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.

defLazyFinger.optimalCostpropext · Classical.choice · Quot.soundBounds/LazyFinger/Definitions/Abstract.lean:40
/-- 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}
defLazyFinger.optimalCostFrompropext · Classical.choice · Quot.soundBounds/LazyFinger/Definitions/Abstract.lean:46
/-- 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 nn 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 nn, every start pp and every sequence, some tree on nn keys has lazy-finger cost exactly optimalCost n xs, and some tree on nn keys has cost from pp exactly optimalCostFrom n p xs.

theoremLazyFinger.Results.optimal_attainedpropext · Classical.choice · Quot.soundBounds/LazyFinger/Abstract.lean:34
/-- 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
theoremLazyFinger.Results.optimal_from_attainedpropext · Classical.choice · Quot.soundBounds/LazyFinger/Abstract.lean:91
/-- 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 xs

These are existence statements. They do not compute the optimal tree. The paper’s O(n3)O(n^3) dynamic program, and its proof of optimality, are the subject of Chapter 27.

Theorem (the optimum is a lower bound). For every tree TT and every sequence, optimalCost(∣T∣,X)≤cost(T,X)\mathtt{optimalCost}(|T|, X) \le \mathtt{cost}(T, X); and the optimum is at least the number of requests.

Combined 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 TT and every sequence XX, optimalCost(∣T∣,X)≤2 StaticTree.cost(T,X)\mathtt{optimalCost}(|T|, X) \le 2\,\mathtt{StaticTree.cost}(T, X).

theoremLazyFinger.Results.optimal_root_fingerpropext · Classical.choice · Quot.soundBounds/LazyFinger/Abstract.lean:42
/-- 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 xs

This 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 kk a weight wkw_k. The mass of a key range counts both endpoints:

defWeightedFinger.masspropext · Classical.choice · Quot.soundBounds/WeightedFinger/Definitions/Abstract.lean:9
/-- Inclusive interval mass; both endpoints contribute. -/noncomputable def mass (w : Nat → ℝ) (x y : Nat) : ℝ :=  ∑ k ∈ Finset.Icc (min x y) (max x y), w k

mass w x y is W(x,y)=∑k=min⁡(x,y)max⁡(x,y)wkW(x, y) = \sum_{k = \min(x,y)}^{\max(x,y)} w_k. It does not depend on the order of xx and yy.

defWeightedFinger.chargepropext · Classical.choice · Quot.soundBounds/WeightedFinger/Definitions/Abstract.lean:13
/-- 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 xx to yy is 1+log⁡2(W(x,y)/min⁡(wx,wy))1 + \log_2\bigl(W(x,y) / \min(w_x, w_y)\bigr). It is small when the range between the two keys is light compared with the lighter endpoint. Think of W(x,y)/wxW(x, y)/w_x as the number of “units of weight wxw_x” that separate the keys. With unit weights it is ∣x−y∣+1|x - y| + 1, 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 11 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 xx to yy is 1+log⁡2(∣x−y∣+1)1 + \log_2(|x - y| + 1), the dynamic finger charge of Bounds.dynamicFingerCostFrom.
  • If wx>0w_x > 0, a repeated key costs exactly 11.
  • The charge is symmetric in xx and yy.
  • Multiplying all weights by the same positive constant does not change the charge.
  • If the weights are positive on the range between xx and yy, the charge is at least 11.
theoremWeightedFinger.Results.unit_weightspropext · Classical.choice · Quot.soundBounds/WeightedFinger/Abstract.lean:9
/-- 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 y
theoremWeightedFinger.Results.repeated_keypropext · Classical.choice · Quot.soundBounds/WeightedFinger/Abstract.lean:15
theorem repeated_key (w : Nat → ℝ) (x : Nat) (hx : 0 < w x) : charge w x x = 1 :=  charge_self w x hx
theoremWeightedFinger.Results.symmetricpropext · Classical.choice · Quot.soundBounds/WeightedFinger/Abstract.lean:18
theorem symmetric (w : Nat → ℝ) (x y : Nat) : charge w x y = charge w y x :=  charge_symm w x y
theoremWeightedFinger.Results.scale_invariantpropext · Classical.choice · Quot.soundBounds/WeightedFinger/Abstract.lean:21
theorem 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 y
theoremWeightedFinger.Results.request_chargepropext · Classical.choice · Quot.soundBounds/WeightedFinger/Abstract.lean:24
theorem 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 hw

Scale invariance means that only the relative weights matter; the weights need not sum to 11. The lower bound 11 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:

defWeightedFinger.costFrompropext · Classical.choice · Quot.soundBounds/WeightedFinger/Definitions/Abstract.lean:18
/-- 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 xs

costFrom w p xs is WDFp(w,X)=∑icw(xi−1,xi)\mathrm{WDF}_p(w, X) = \sum_i c_w(x_{i-1}, x_i) with x0=px_0 = p, the weighted dynamic finger bound of Iacono and Langerman. The optimal choice of weights gives a function of the sequence alone:

defWeightedFinger.optimalCostFrompropext · Classical.choice · Quot.soundBounds/WeightedFinger/Definitions/Abstract.lean:23
/-- 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 0,…,n−10, \dots, n-1. Values of ww outside that range are unconstrained, and on valid requests the charges never read them.

Reading the Lean
  • 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 min⁡W\min_W.
  • Valid inputs. In Lean, sInf of a set of reals that is not bounded below is 00. The library proves the lower bound mm for the set when the start and the requests are keys, so every theorem about optimalCostFrom assumes p<np < n and that every request is less than nn.
  • A start key. The weighted bound always starts from a key pp. Unlike a tree, a weighting has no root to start from.

Under those hypotheses the optimum behaves as expected.

Theorem (the weight optimum). Let p<np < n and let every request be less than nn. Then WDFp(X)≥m\mathrm{WDF}_p(X) \ge m, and WDFp(X)≤WDFp(w,X)\mathrm{WDF}_p(X) \le \mathrm{WDF}_p(w, X) for every weighting ww positive on the nn keys.

theoremWeightedFinger.Results.optimal_request_chargepropext · Classical.choice · Quot.soundBounds/WeightedFinger/Abstract.lean:28
/-- 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 valid
theoremWeightedFinger.Results.optimal_lepropext · Classical.choice · Quot.soundBounds/WeightedFinger/Abstract.lean:33
/-- 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 valid

15.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 aa is an ancestor of xx exactly when aa comes first, among the keys between aa and xx, in the order, and under weighted sampling that happens with probability wa/W(a,x)w_a / W(a, x). Averaging the ancestor-event formula of Section 15.2 gives the expected distance exactly.

Theorem (expected distance in a weighted treap). Let ww be positive on the keys lo,…,lo+n−1lo, \dots, lo + n - 1. There is an assignment σ↦Tσ\sigma \mapsto T_\sigma of a tree on nn nodes to every order, such that for all keys x,yx, y in the range,

Eσ[dTσ(x,y)]  =  ∑a(waW(a,x)+waW(a,y)−2 waW(min⁡(a,x,y),max⁡(a,x,y))),\mathbb E_\sigma\bigl[d_{T_\sigma}(x, y)\bigr] \;=\; \sum_{a} \Bigl(\frac{w_a}{W(a, x)} + \frac{w_a}{W(a, y)} - 2\,\frac{w_a}{W(\min(a,x,y), \max(a,x,y))}\Bigr),

where aa ranges over the keys and the expectation is over the weighted random order.

theoremLazyFinger.Random.Results.expected_distancepropext · Classical.choice · Quot.soundBounds/LazyFinger/Random/Abstract.lean:10
/-- 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 hw

The tree TσT_\sigma holds the ranks 0,…,n−10, \dots, n-1 and stands for the keys lo,…,lo+n−1lo, \dots, lo + n - 1; hence x - lo in the statement. The third term is the probability that aa is a common ancestor: it must come first in the smallest range containing aa, xx and yy. 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 aa into those below, between and above xx and yy. For a key outside the range, the term is a difference of two probabilities, such as wa/W(a,x)−wa/W(a,y)w_a / W(a, x) - w_a / W(a, y) for a<x≤ya < x \le y, 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 wa/W(x,a)w_a / W(x, a), and the inequality b/(a+b)≤ln⁡(a+b)−ln⁡ab/(a + b) \le \ln(a + b) - \ln a compares their sum with the growth of ln⁡W(x,a)\ln W(x, a) as aa moves from xx to yy. The library obtains 4ln⁡(W(x,y)/min⁡(wx,wy))4 \ln\bigl(W(x,y)/\min(w_x, w_y)\bigr) for the expected distance, then replaces ln⁡\ln by log⁡2\log_2 and adds the request charge.

Theorem 1 (a random tree realizes the weights). Let ww be positive on {0,…,n−1}\{0, \dots, n-1\}. There is an assignment σ↦Tσ\sigma \mapsto T_\sigma of a tree on nn nodes to every order such that, for all keys x,y<nx, y < n,   Eσ[1+dTσ(x,y)]≤4 cw(x,y)\;\mathbb E_\sigma[1 + d_{T_\sigma}(x, y)] \le 4\,c_w(x, y).

theoremLazyFinger.Random.Results.weighted_chargepropext · Classical.choice · Quot.soundBounds/LazyFinger/Random/Abstract.lean:22
/-- 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 hw

The quantifiers carry the content. The family TT is chosen after ww and nn and before xx and yy, 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 O(log⁡2(W/min⁡))O(\lg(W/\min)) without the request charge; the library’s form, with the unit on both sides, has the explicit constant 44.

Two statements, two families

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 ww be positive on {0,…,n−1}\{0, \dots, n-1\}, let p<np < n, and let XX be a sequence of keys less than nn. There is a tree TT on nn keys with LFp(T,X)≤4 WDFp(w,X)\mathrm{LF}_p(T, X) \le 4\,\mathrm{WDF}_p(w, X).

theoremLazyFinger.Results.tree_for_weightspropext · Classical.choice · Quot.soundBounds/LazyFinger/Abstract.lean:82
/-- 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

The proof sums Theorem 1 over the consecutive pairs of XX, so that the expected cost of TσT_\sigma is at most 4 WDFp(w,X)4\,\mathrm{WDF}_p(w, X), and then picks an order σ\sigma 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 XX without changing.

The converse direction represents a given tree by weights. The proof gives a key at depth dd the weight 4−(d+1)4^{-(d+1)}, the same weights as in the proof of the entropy bound of Chapter 14. (The paper uses 4−d4^{-d}; the constant factor cancels in every charge, by scale invariance.)

  • Lower bound on the charge. The range between xx and yy contains their LCA, whose weight is 4−(ℓ+1)4^{-(\ell + 1)} for ℓ\ell its depth. The lighter endpoint has weight 4−(max⁡(dx,dy)+1)4^{-(\max(d_x, d_y) + 1)}. So the mass ratio is at least 4max⁡(dx,dy)−ℓ4^{\max(d_x, d_y) - \ell}, and its logarithm at least 2max⁡(dx,dy)−2ℓ≥dx+dy−2ℓ=dT(x,y)2\max(d_x,d_y) - 2\ell \ge d_x + d_y - 2\ell = d_T(x, y).
  • Upper bound on the charge. The range between xx and yy lies inside the subtree of their LCA. In that subtree the weights decrease by a factor of 44 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 2 (max⁡(dx,dy)−ℓ)≤2 dT(x,y)2\,(\max(d_x, d_y) - \ell) \le 2\,d_T(x, y).

Lemma 3 (trees give weights). For every tree TT there is a weighting ww, positive everywhere, such that for all keys x,yx, y of TT,   1+dT(x,y)≤cw(x,y)≤3+2 dT(x,y)\;1 + d_T(x, y) \le c_w(x, y) \le 3 + 2\,d_T(x, y). Consequently, for every key pp of TT and every sequence XX of keys of TT,   LFp(T,X)≤WDFp(w,X)≤3 LFp(T,X)\;\mathrm{LF}_p(T, X) \le \mathrm{WDF}_p(w, X) \le 3\,\mathrm{LF}_p(T, X).

theoremLazyFinger.Results.tree_weights_two_sidedpropext · Classical.choice · Quot.soundBounds/LazyFinger/Abstract.lean:131
/-- 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

The weighting depends on TT only: one weighting works for every pair, every start and every sequence. The sequence bounds follow by summing the pairwise bounds, using 3+2d≤3 (1+d)3 + 2d \le 3\,(1 + d).

Corollary 4 (the reverse comparison). For every tree TT there is a weighting ww, positive everywhere, with cw(x,y)≤3+2 dT(x,y)c_w(x, y) \le 3 + 2\,d_T(x, y) for all keys x,yx, y of TT, and WDFp(w,X)≤3 LFp(T,X)\mathrm{WDF}_p(w, X) \le 3\,\mathrm{LF}_p(T, X) for every key pp and every sequence XX of keys of TT.

theoremLazyFinger.Results.tree_weightspropext · Classical.choice · Quot.soundBounds/LazyFinger/Abstract.lean:49
/-- 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 t

Corollary 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.

Compared with the paper

The paper’s Lemma 3 states the lower bound on the charge, r(T,i,j)≤log⁡2(W(i,j)/min⁡(wi,wj))r(T, i, j) \le \lg\bigl(W(i,j)/\min(w_i, w_j)\bigr), and its proof shows log⁡2(⋅)≥2 r(T,i,j)\lg(\cdot) \ge 2\,r(T, i, j). Its Corollary 4, ∑ir(T,xi−1,xi)=Ω(min⁡W∑ilog⁡2(⋅))\sum_i r(T, x_{i-1}, x_i) = \Omega(\min_W \sum_i \lg(\cdot)), needs the opposite comparison, log⁡2(⋅)=O(1+r(T,i,j))\lg(\cdot) = O(1 + r(T, i, j)) 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 ww: Corollary 2 gives a tree of cost at most 4 WDFp(w,X)4\,\mathrm{WDF}_p(w, X), so the optimal tree costs at most that much, and taking the infimum over ww gives LFp≤4 WDFp\mathrm{LF}_p \le 4\,\mathrm{WDF}_p. For the lower bound, take an optimal tree, which exists by attainment: Corollary 4 gives a weighting whose weighted cost is at most 3 LFp3\,\mathrm{LF}_p, and the infimum over weights is at most that.

Theorem 5 (characterization from a common start). Let p<np < n and let XX be a sequence of keys less than nn. Then WDFp(X)≤3 LFp(X)\mathrm{WDF}_p(X) \le 3\,\mathrm{LF}_p(X) and LFp(X)≤4 WDFp(X)\mathrm{LF}_p(X) \le 4\,\mathrm{WDF}_p(X).

theoremLazyFinger.Results.characterization_frompropext · Classical.choice · Quot.soundBounds/LazyFinger/Abstract.lean:96
/-- 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

This 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 nn, and gives the root-start form.

Theorem 5 (root start). Let p<np < n and let XX be a sequence of keys less than nn. Then WDFp(X)≤3 (LF(X)+n)\mathrm{WDF}_p(X) \le 3\,(\mathrm{LF}(X) + n) and LF(X)≤n+4 WDFp(X)\mathrm{LF}(X) \le n + 4\,\mathrm{WDF}_p(X).

theoremLazyFinger.Results.characterization_rootpropext · Classical.choice · Quot.soundBounds/LazyFinger/Abstract.lean:110
/-- 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 valid

On the weighted side, pp is any key: the comparison holds for every choice of start for the weights simultaneously. Adding nn to both benchmarks makes the two inequalities symmetric:

Theorem 5 (with startup). Under the same hypotheses, LF(X)+n≤4 (WDFp(X)+n)\mathrm{LF}(X) + n \le 4\,(\mathrm{WDF}_p(X) + n) and WDFp(X)+n≤4 (LF(X)+n)\mathrm{WDF}_p(X) + n \le 4\,(\mathrm{LF}(X) + n).

theoremLazyFinger.Results.characterizationpropext · Classical.choice · Quot.soundBounds/LazyFinger/Abstract.lean:117
/-- 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

On long sequences the additive term disappears, because both benchmarks charge at least one unit per request, so each is at least m≥nm \ge n.

Theorem 5 (long sequences). If moreover n≤mn \le m, then WDFp(X)≤6 LF(X)\mathrm{WDF}_p(X) \le 6\,\mathrm{LF}(X) and LF(X)≤5 WDFp(X)\mathrm{LF}(X) \le 5\,\mathrm{WDF}_p(X).

theoremLazyFinger.Results.characterization_long_sequencepropext · Classical.choice · Quot.soundBounds/LazyFinger/Abstract.lean:124
/-- 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 long
Compared with the paper

The paper states Theorem 5 as min⁡T∑ir(T,xi−1,xi)=Θ(min⁡W∑ilog⁡2(W(xi−1,xi)/min⁡(wxi−1,wxi)))\min_T \sum_i r(T, x_{i-1}, x_i) = \Theta\bigl(\min_W \sum_i \lg(W(x_{i-1}, x_i) / \min(w_{x_{i-1}}, w_{x_i}))\bigr), with x0x_0 the root of TT. 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 pp. The tree side starts either from the same key (characterization_from) or from the root, at the price of an additive nn (characterization_root, characterization) or of the assumption m≥nm \ge n (characterization_long_sequence).
  • Infimum. The minimum over weights is an infimum; the minimum over trees is attained.
  • Constants. All constants are explicit, and log⁡2\log_2 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 xx to yy uses that edge exactly when one of x,yx, y 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.

defLazyFinger.cutno axiomsBounds/LazyFinger/Edges/Definitions/Abstract.lean:8
/-- 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
defLazyFinger.intervalCostno axiomsBounds/LazyFinger/Edges/Definitions/Abstract.lean:13
/-- 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)
defLazyFinger.edgeMovementno axiomsBounds/LazyFinger/Edges/Definitions/Abstract.lean:22
/-- 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
defLazyFinger.crossingsno axiomsBounds/LazyFinger/Edges/Definitions/Abstract.lean:27
/-- 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 xs
  • cut lo hi x y is 11 if exactly one of x,yx, y lies in the half-open range [lo,hi)[lo, hi), and 00 otherwise.
  • intervalCost w t lo sums a toll w lo hi over the key ranges of all nonempty subtrees of t, whose keys start at lo, including t itself. 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 y uses the toll cut: it counts the subtrees separating xx from yy, that is, the edges of the path between them, plus the incoming edge if only one endpoint is inside. The endpoints may lie outside t, which is what lets the movement of a global sequence be split among subtrees.
  • crossings lo hi p xs counts the consecutive pairs of the sequence, from x0=px_0 = p, that cross the boundary of [lo,hi)[lo, hi).

The basic facts are the three cases of a single move.

Theorem (one move, by subtrees). Let TT have keys lo,…,lo+n−1lo, \dots, lo + n - 1. If neither xx nor yy is a key of TT, the move uses no edge of TT and does not enter it. If xx is a key of TT and yy is not, it uses the path from xx to the root of TT and the edge above it, depth(x)+1\mathrm{depth}(x) + 1 edges. If both are keys of TT, it uses exactly dT(x,y)d_T(x, y) edges, and the whole tree’s own range contributes nothing.

theoremLazyFinger.Edges.Results.outsidepropext · Classical.choice · Quot.soundBounds/LazyFinger/Edges/Abstract.lean:9
/-- 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 hy
theoremLazyFinger.Edges.Results.enteringpropext · Classical.choice · Quot.soundBounds/LazyFinger/Edges/Abstract.lean:15
/-- 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 hy
theoremLazyFinger.Edges.Results.distancepropext · Classical.choice · Quot.soundBounds/LazyFinger/Edges/Abstract.lean:21
/-- 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 hy

Summing 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 TT, every key pp and every sequence XX of keys of TT,   LFp(T,X)=m+∑Scrossings(S,p,X)\;\mathrm{LF}_p(T, X) = m + \sum_{S} \mathrm{crossings}(S, p, X), where SS ranges over the key ranges of the nonempty subtrees of TT, including TT’s own.

theoremLazyFinger.Edges.Results.sequencepropext · Classical.choice · Quot.soundBounds/LazyFinger/Edges/Abstract.lean:27
/-- 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 valid

The root start fits the same form. Start the sequence instead at the key nn, 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 TT on nn keys and every sequence XX of its keys,   cost(T,X)+[X≠∅]=m+∑Scrossings(S,n,X)\;\mathtt{cost}(T, X) + [X \ne \varnothing] = m + \sum_S \mathrm{crossings}(S, n, X).

theoremLazyFinger.Edges.Results.initializationpropext · Classical.choice · Quot.soundBounds/LazyFinger/Edges/Abstract.lean:33
/-- 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 valid

The correction [X≠∅][X \neq \varnothing] 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 CC. If ss rotates to tt, then the interval cost of tt is at most that of ss plus CC. In particular, if every range is crossed at most CC times by a sequence XX from pp, then one rotation increases LFp(⋅,X)\mathrm{LF}_p(\cdot, X) by at most CC.

theoremLazyFinger.Edges.Results.rotationpropext · Quot.soundBounds/LazyFinger/Edges/Abstract.lean:41
/-- 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 lo
theoremLazyFinger.Edges.Results.sequence_rotationpropext · Classical.choice · Quot.soundBounds/LazyFinger/Edges/Abstract.lean:47
/-- 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 bounded

Rotate 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:

defLazyFinger.frequencyno axiomsBounds/LazyFinger/Frequencies/Definitions/Abstract.lean:9
/-- 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
defLazyFinger.frequencyTollpropext · Classical.choice · Quot.soundBounds/LazyFinger/Frequencies/Definitions/Abstract.lean:14
/-- 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 b

frequency p xs a b is the paper’s fX(a,b)f_X(a, b): the number of indices ii with xi−1=ax_{i-1} = a and xi=bx_i = b, counting the initial pair (p,x1)(p, x_1). frequencyToll n f lo hi sums f(a,b)f(a, b) over the pairs of keys a,b<na, b < n that cross the boundary of [lo,hi)[lo, hi). 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 n×nn \times n 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.