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

Chapter 24 · Splay trees · Section 24.3Beyond single accesses

The theorems of Section 24.2 are about one algorithm serving accesses to a fixed set of keys. Splay trees do more. Sleator and Tarjan show that insertion, deletion, split and join also cost O(log⁡n)O(\log n) amortized, so a splay tree is a complete dictionary with the same guarantee. Their paper also analyses a variant that splays only along long paths, and the expected shape of the tree under random requests (the snapshot). Tarjan (1985) later proved the scanning theorem: accessing every key once, in increasing order, costs O(n)O(n) from any initial tree. The library proves versions of all four. The two headline results are the dictionary bound and the scanning theorem:

Key result · Sleator and Tarjan 1985
Splay trees support updates in O(log⁡n)O(\log n) amortized time

Consider any sequence of mm operations on a collection of splay trees (a forest). Each operation is an access, an insertion, a deletion, a split of one tree into two, or a join of two trees, and is charged one unit plus its rotations. Suppose the forest never holds more than NN keys, and initially holds ss keys. Then the total cost is at most

m (5log⁡2(N+1)+3)+slog⁡2(s+1).m\,\bigl(5\log_2(N+1) + 3\bigr) + s\log_2(s+1).

In Lean, the operations are Updates.split, Updates.join, Updates.insert and Updates.delete, built on Splay.run. A run of operations is an Updates.Execution made of Updates.Steps, and balance is the bound. Insertions and deletions name their position by rank; the search that finds that rank from a key is not modelled (Section 24.3.1).

The Lean statement
theoremSplay.Updates.Results.balancepropext · Classical.choice · Quot.soundAlgorithms/Splay/Updates/Abstract.lean:36
/-- Balance theorem with access, insertion, deletion, split, and join.At most `N` keys are stored across the forest; `m` is the number of operations.Cost `c` includes one unit per operation and every splay rotation. -/theorem balance (execution : Execution N s m t c) :    (c : ℝ) ≤ (m : ℝ) * (5 * Real.logb 2 (N + 1 : Nat) + 3) +      (forestSize s : ℝ) * Real.logb 2 (forestSize s + 1 : Nat) := …  Updates.balance execution
15 definitions in 4 chapters · reading list
Key result · Tarjan 1985
Sequential access in splay trees takes linear time

For every initial tree on nn keys, accessing the keys 0,1,…,n−10, 1, \dots, n-1 in increasing order by splaying costs at most 14n14n in total, counting one unit per request plus one per rotation. The first access alone may take n−1n-1 rotations, so the bound is about the whole scan, not about each access.

In Lean, the scan is List.range t.size, and scanning bounds totalCost of Splay.algorithm.

The Lean statement
theoremSplay.Results.scanningpropext · Classical.choice · Quot.soundAlgorithms/Splay/Scanning/Abstract.lean:14
/-- Accessing every key once in increasing order takes linear total cost. -/theorem scanning (t : Tree) :    algorithm.totalCost t (List.range t.size) ≤ 14 * t.size := …  Scanning.total_bound t
15 definitions in 6 chapters · reading list

Each of these results comes with modelling choices that are easy to misread, so this section spends more time on the definitions than on the bounds.

24.3.1 Updates

24.3.1.1 The four operations on shapes

Updates change the key set, so ranks must change too. The library keeps the shape view: every tree uses its own inorder ranks 0,…,n−10, \dots, n-1, and an operation’s effect on keys is a statement about how ranks are renumbered. A gap k∈{0,…,n}k \in \{0, \dots, n\} is the position between ranks k−1k-1 and kk, as in Chapter 1.

structureSplay.Updates.SplitResultno axiomsAlgorithms/Splay/Updates/Algorithm/Abstract.lean:13
structure SplitResult where  left : Tree  right : Tree  cost : Nat  deriving DecidableEq, Repr
defSplay.Updates.splitno axiomsAlgorithms/Splay/Updates/Algorithm/Abstract.lean:19
/-- Split before rank `k` by splaying its predecessor. Valid gaps satisfy `k ≤ size`. -/def split (t : Tree) (k : Nat) : SplitResult :=  if k = 0 then ⟨.nil, t, 0⟩ else    let (u, c) := run t (k - 1)    match u with    | .nil => ⟨.nil, .nil, c⟩    | .node l r => ⟨.node l .nil, r, c⟩

split t k cuts t into the first k keys and the rest. For k = 0 there is nothing to do: the left part is empty and the cost is zero. Otherwise it splays the predecessor of the gap, rank k−1k-1, to the root, and cuts the edge to its right child. The root, with its left subtree, becomes the left tree, and the former right subtree becomes the right tree. Both keep their local ranks, so key kk of t becomes rank 00 of the right tree. The .nil branch of the match is unreachable for valid gaps, since splaying an existing rank never yields an empty tree. It only makes the function total.

defSplay.Updates.joinno axiomsAlgorithms/Splay/Updates/Algorithm/Abstract.lean:27
/-- Join two ordered key sets by splaying the maximum of the left tree. -/def join (l r : Tree) : Tree × Nat :=  match l with  | .nil => (r, 0)  | .node _ _ =>      let (u, c) := run l (l.size - 1)      match u with      | .nil => (r, c)      | .node a _ => (.node a r, c)

join l r concatenates two key sets, all of l before all of r. On shapes this needs no hypothesis: the joined tree’s inorder is l’s keys followed by r’s, by construction. It splays the maximum of l, rank l.size - 1, which leaves a root with an empty right subtree, and hangs r there. The pattern .node a _ discards that right subtree, which is .nil after splaying the maximum (Updates.run_max proves this).

defSplay.Updates.insertno axiomsAlgorithms/Splay/Updates/Algorithm/Abstract.lean:37
/-- Insert a new key in gap `k`, making that key the root. -/def insert (t : Tree) (k : Nat) : Tree × Nat :=  let s := split t k  (.node s.left s.right, s.cost)
defSplay.Updates.deleteno axiomsAlgorithms/Splay/Updates/Algorithm/Abstract.lean:42
/-- Delete existing rank `x`: splay it, remove the root, and join its children. -/def delete (t : Tree) (x : Nat) : Tree × Nat :=  let (u, c) := run t x  match u with  | .nil => (.nil, c)  | .node l r =>      let (v, d) := join l r      (v, c + d)

insert t k puts a new key into gap k: split there and make the new key the root over the two halves. Its rank is k, and every old rank at or after k increases by one. delete t x splays x, removes the root, and joins its subtrees, so every rank after x decreases by one. The counts returned are rotations only. The unit charge for the operation itself is added by the execution model below.

Reading the Lean
  • The insertion position is a rank supplied by the caller. Finding that rank from a new comparison key, by searching for it, is not formalized. Neither is a pointer machine with node allocation; the README lists both as remaining work.
  • Out-of-range arguments (k > t.size for split, x ≥ t.size for delete) are outside every theorem below, which all assume validity.

The size lemmas confirm the renumbering.

Theorem (sizes). For valid arguments on a tree with nn keys, splitting at gap kk gives trees with kk and n−kn - k keys, joining gives ∣l∣+∣r∣|l| + |r| keys, insertion adds one key and deletion removes one. A split at k>0k > 0 is a certified splay access to rank k−1k - 1, followed by cutting the root’s right edge (split_spec).

theoremSplay.Updates.Results.split_sizespropext · Quot.soundAlgorithms/Splay/Updates/Abstract.lean:16
theorem split_sizes (t : Tree) (k : Nat) (valid : k ≤ t.size) :    (split t k).left.size = k ∧ (split t k).right.size = t.size - k :=  Updates.split_sizes t k valid
theoremSplay.Updates.Results.split_specpropext · Quot.soundAlgorithms/Splay/Updates/Abstract.lean:20
/-- A nontrivial split consists of a certified predecessor access and one cut. -/theorem split_spec (t : Tree) (k : Nat) (valid : k ≤ t.size) (positive : 0 < k) :    ∃ l r c, Access t (.node l r) (k - 1) c ∧ split t k = ⟨.node l .nil, r, c⟩ :=  Updates.split_spec t k valid positive
theoremSplay.Updates.Results.join_sizepropext · Quot.soundAlgorithms/Splay/Updates/Abstract.lean:25
theorem join_size (l r : Tree) : (join l r).1.size = l.size + r.size :=  Updates.join_size l r
theoremSplay.Updates.Results.insert_sizepropext · Quot.soundAlgorithms/Splay/Updates/Abstract.lean:28
theorem insert_size (t : Tree) (k : Nat) (valid : k ≤ t.size) :    (insert t k).1.size = t.size + 1 :=  Updates.insert_size t k valid
theoremSplay.Updates.Results.delete_sizepropext · Quot.soundAlgorithms/Splay/Updates/Abstract.lean:32
theorem delete_size (t : Tree) (x : Nat) (valid : x < t.size) :    (delete t x).1.size = t.size - 1 :=  Updates.delete_size t x valid

24.3.1.2 Forests and charged operations

Splits create several trees and joins consume them, so the state of an execution is a list of trees, a forest.

defSplay.Updates.forestSizeno axiomsAlgorithms/Splay/Updates/Execution/Abstract.lean:9
/-- Number of stored keys across the forest. -/def forestSize (ts : List Tree) : Nat := (ts.map Tree.size).sum
inductiveSplay.Updates.Stepno axiomsAlgorithms/Splay/Updates/Execution/Abstract.lean:12
/-- Standard successful operations, charged one unit plus their rotations.`Step s t c n` records cost `c` and `n` participating keys before the operation.Unrelated trees may be carried along; reordering the list of tree handles is free.`join` requires that the left key set precede the right one; each input tree useslocal inorder ranks, and the joined tree uses their concatenation. -/inductive Step : List Tree → List Tree → Nat → Nat → Prop where  | access {x : Nat} {t : Tree} (valid : x < t.size) : Step [t] [(run t x).1] ((run t x).2 + 1) t.size  | insert {k : Nat} {t : Tree} (valid : k ≤ t.size) : Step [t] [(insert t k).1] ((insert t k).2 + 1) t.size  | delete {x : Nat} {t : Tree} (valid : x < t.size) : Step [t] [(delete t x).1] ((delete t x).2 + 1) t.size  | split {k : Nat} {t : Tree} (valid : k ≤ t.size) : Step [t] [(split t k).left, (split t k).right] ((split t k).cost + 1) t.size  | join {l r : Tree} : Step [l, r] [(join l r).1] ((join l r).2 + 1) (l.size + r.size)  | frame {s t : List Tree} {k n : Nat} {a : Tree} : Step s t k n → Step (a :: s) (a :: t) k n  | rearrange {s s' t' : List Tree} {k n : Nat} {t : List Tree} : s.Perm s' → Step s' t' k n → t'.Perm t → Step s t k n

Step s t c n is one successful operation: forest s becomes forest t at cost c, and n is the number of keys taking part. The five operation constructors act on a forest with exactly the involved trees. The cost is always the rotation count plus one, and n is the size of the involved tree, or l.size + r.size for a join. Validity hypotheses are part of the constructors: k ≤ t.size for insert and split, x < t.size for access and delete.

The last two constructors are structural:

  • frame carries an unrelated tree a along unchanged, without changing the cost or n. Repeated use lets an operation act on any trees of a larger forest while the rest is untouched, and those untouched trees contribute nothing to n.
  • rearrange lets the forest be permuted before and after an operation, for free. The list is just a collection of tree handles; its order means nothing.

join takes the first two trees in that order: the left one’s keys come first. Combined with rearrange, any two trees can be joined in either order, which is legitimate because each tree has its own local ranks. Nothing in the model records a global key universe. Joining two trees means only that one key set is declared to precede the other.

inductiveSplay.Updates.Executionno axiomsAlgorithms/Splay/Updates/Execution/Abstract.lean:26
/-- `m` operations, total cost `c`, with at most `N` stored keys at every boundary. -/inductive Execution (N : Nat) : List Tree → Nat → List Tree → Nat → Prop where  | nil {s : List Tree} (bound : forestSize s ≤ N) : Execution N s 0 s 0  | cons {s t : List Tree} {k n m : Nat} {u : List Tree} {c : Nat} (bound : forestSize s ≤ N) : Step s t k n → Execution N t m u c →      Execution N s (m + 1) u (k + c)
inductiveSplay.Updates.LocalExecutionno axiomsAlgorithms/Splay/Updates/Execution/Abstract.lean:32
/-- An unbounded execution records the size of the tree(s) involved in eachoperation. Unrelated trees do not contribute to that operation's logarithm. -/inductive LocalExecution : List Tree → List Nat → List Tree → Nat → Prop where  | nil {s : List Tree} : LocalExecution s [] s 0  | cons {s t : List Tree} {k n : Nat} {ns : List Nat} {u : List Tree} {c : Nat} : Step s t k n → LocalExecution t ns u c → LocalExecution s (n :: ns) u (k + c)

Execution N s m t c is a sequence of m operations with total cost c, during which the forest never holds more than N keys. The bound hypothesis is checked at every boundary, including the final forest. LocalExecution s ns t c drops the global bound and instead records the list ns of participating key counts, one per operation.

24.3.1.3 Balance with updates

Theorem (balance with updates). Consider an execution of mm operations during which the forest never holds more than NN keys, starting from a forest with ss keys in total. Its total cost is at most m (5log⁡2(N+1)+3)+slog⁡2(s+1)m\,(5\log_2(N+1) + 3) + s\log_2(s+1). If the forest starts empty, the total cost is at most ∑j(5log⁡2(nj+1)+3)\sum_j \bigl(5\log_2(n_j + 1) + 3\bigr), where njn_j is the number of keys in the trees that operation jj involves.

theoremSplay.Updates.Results.balancepropext · Classical.choice · Quot.soundAlgorithms/Splay/Updates/Abstract.lean:36
/-- Balance theorem with access, insertion, deletion, split, and join.At most `N` keys are stored across the forest; `m` is the number of operations.Cost `c` includes one unit per operation and every splay rotation. -/theorem balance (execution : Execution N s m t c) :    (c : ℝ) ≤ (m : ℝ) * (5 * Real.logb 2 (N + 1 : Nat) + 3) +      (forestSize s : ℝ) * Real.logb 2 (forestSize s + 1 : Nat) :=  Updates.balance execution
theoremSplay.Updates.Results.balance_initially_emptypropext · Classical.choice · Quot.soundAlgorithms/Splay/Updates/Abstract.lean:44
/-- Sharper, operation-sensitive bound, exactly for initially empty trees.The list `ns` records only the keys involved in each operation, not the entire forest. -/theorem balance_initially_empty (execution : LocalExecution s ns t c) (empty : forestSize s = 0) :    (c : ℝ) ≤ (ns.map fun n : Nat => 5 * Real.logb 2 (n + 1 : Nat) + 3).sum :=  Updates.balance_initially_empty execution empty

The first theorem is the analogue of the balance theorem for arbitrary initial forests, with a startup term for the initial forest. The second is the paper’s version, in which an operation pays only for the keys of the trees it touches: a small tree is cheap to operate on even when the forest is large.

Proof sketch

The potential is the unit-weight splay potential (Section 24.2), summed over the trees of the forest; permuting the forest leaves it unchanged. Each operation is bounded separately using the access lemma with unit weights, i.e. R+ΔΦ≤3log⁡2n+1R + \Delta\Phi \le 3\log_2 n + 1: splitting adds nothing beyond the access, because cutting the root’s right edge only lowers the root’s subtree size. Joining is an access to the maximum of ll, after which the root’s rank grows from log⁡2∣l∣\log_2|l| to log⁡2(∣l∣+∣r∣)\log_2(|l|+|r|), giving 3log⁡2(∣l∣+∣r∣)+13\log_2(|l|+|r|)+1 in total. Insertion is a split plus a new root, giving 4log⁡2(n+1)+14\log_2(n+1)+1. Deletion is an access plus a join, giving 5log⁡2n+25\log_2 n + 2. With the unit charge, every case is at most 5log⁡2(n+1)+35\log_2(n+1)+3. The initial potential is at most ∣s∣log⁡2(∣s∣+1)|s|\log_2(|s|+1) and the final potential is nonnegative. See Algorithms/Splay/Updates/Potential.lean and Balance.lean.

24.3.2 Long splays

Section 5 of the paper considers splaying less often. A conditional splay searches for xx as usual, but restructures only if the search path is long. The library fixes positive weights ww and the threshold that makes the access lemma pay for itself:

defSplay.conditionalSteppropext · Classical.choice · Quot.soundAlgorithms/Splay/Conditional/Algorithm/Abstract.lean:13
/-- Splay only paths at least twice the access lemma's amortized charge.The fixed positive weights belong to this variant's decision rule. -/noncomputable def conditionalStep (w : Nat → ℝ) (t : Tree) (x : Nat) : Tree × Nat := by  classical  exact if 6 * (Real.logb 2 (mass w t 0) - Real.logb 2 (w x)) + 2 ≤ (run t x).2    then run t x else (t, 0)
defSplay.conditionalRunpropext · Classical.choice · Quot.soundAlgorithms/Splay/Conditional/Algorithm/Abstract.lean:20
/-- Execute conditional searches and accumulate only their restructuring cost. -/noncomputable def conditionalRun (w : Nat → ℝ) : Tree → List Nat → Tree × Nat  | t, [] => (t, 0)  | t, x :: xs =>      let (u, k) := conditionalStep w t x      let (v, m) := conditionalRun w u xs      (v, k + m)

conditionalStep w t x splays exactly when the depth of x, which is (run t x).2 (Section 24.1), is at least 6(log⁡2W−log⁡2w(x))+26(\log_2 W - \log_2 w(x)) + 2, twice the amortized bound of the access lemma, with WW = mass w t 0. Otherwise it returns the tree unchanged at cost zero. conditionalRun sums these costs over a request sequence.

Reading the Lean
  • The weights are part of the algorithm here, unlike everywhere else in this chapter, where they are ghost data of the analysis. Comparing reals is not computable, so the definition is noncomputable and decides the threshold classically.
  • WW is the total weight of the current tree. Weights are indexed by rank and rotations preserve ranks, so WW is the same for every tree reached.
  • The returned number counts restructuring rotations only. A short search that does not splay still walks to xx; it is not a zero-cost root access, and the conditional variant is not an Algorithm in the sense of Chapter 5, because the tree it leaves need not have xx at the root. Its search cost is accounted for separately in the pointer model: Splay.conditionalStep_pointer shows that each conditional step is served by a pointer search of cost at most 1+3⋅depth1 + 3 \cdot \text{depth}.

Theorem (long splays). Fix positive weights ww, and let WW be the total weight of the nn keys. For every initial tree and every sequence of valid requests, conditional splaying performs at most 2∑i<nlog⁡2(W/w(i))2\sum_{i<n} \log_2(W/w(i)) restructuring rotations in total. With unit weights, this is at most 2nlog⁡2n2n\log_2 n.

theoremSplay.Results.long_splaypropext · Classical.choice · Quot.soundAlgorithms/Splay/Conditional/Abstract.lean:13
theorem long_splay (w : Nat → ℝ) (positive : ∀ i, 0 < w i)    (t : Tree) (xs : List Nat) (valid : ∀ x ∈ xs, x < t.size) :    ((conditionalRun w t xs).2 : ℝ) ≤      2 * ∑ i ∈ Finset.range t.size, Real.logb 2 (mass w t 0 / w i) :=  Splay.long_splay w positive t xs valid
theoremSplay.Results.long_splay_unitpropext · Classical.choice · Quot.soundAlgorithms/Splay/Conditional/Abstract.lean:19
theorem long_splay_unit (t : Tree) (xs : List Nat) (valid : ∀ x ∈ xs, x < t.size) :    ((conditionalRun (fun _ => 1) t xs).2 : ℝ) ≤ 2 * (t.size : ℝ) * Real.logb 2 t.size :=  Splay.long_splay_unit t xs valid

The bound is independent of the length of xs: once the tree is shaped so that every key is shallow relative to its weight, conditional splaying stops restructuring altogether. It says nothing about the total search cost, which still grows with the number of requests.

Proof sketch

When a splay is performed, the depth RR is at least twice the access lemma’s charge 3(log⁡2W−log⁡2w(x))+13(\log_2 W - \log_2 w(x)) + 1, so R+ΔΦ≤R/2R + \Delta\Phi \le R/2, i.e. R≤2(Φbefore−Φafter)R \le 2(\Phi_{\text{before}} - \Phi_{\text{after}}). When no splay happens, both sides are zero. Summing telescopes to 2(Φ0−Φfinal)2(\Phi_0 - \Phi_{\text{final}}). Every subtree’s mass lies between the weight of its root and WW, so the total drop is at most ∑i(log⁡2W−log⁡2w(i))\sum_i (\log_2 W - \log_2 w(i)).

24.3.3 The snapshot theorem

Suppose requests are independent and key xx is requested with probability p(x)p(x). Stop the splay tree at a random moment and freeze it as a static search tree. The snapshot theorem says that the frozen tree is, in expectation, nearly entropy-optimal. The library models this with explicit finite sums, without measure theory:

defSplay.meanSearchpropext · Classical.choice · Quot.soundAlgorithms/Splay/Snapshot/Definitions/Abstract.lean:13
/-- Mean static search cost in this tree, including one unit for the request.Splay's rotation count equals the ordinary search depth. -/noncomputable def meanSearch (n : Nat) (p : Nat → ℝ) (t : Tree) : ℝ :=  1 + ∑ x ∈ Finset.range n, p x * (run t x).2
defSplay.snapshotAtpropext · Classical.choice · Quot.soundAlgorithms/Splay/Snapshot/Definitions/Abstract.lean:18
/-- Expected static search cost of the tree after exactly `j` independent accesses. -/noncomputable def snapshotAt (n : Nat) (p : Nat → ℝ) (t : Tree) : Nat → ℝ  | 0 => meanSearch n p t  | j + 1 => ∑ x ∈ Finset.range n, p x * snapshotAt n p (run t x).1 j
defSplay.snapshotMeanpropext · Classical.choice · Quot.soundAlgorithms/Splay/Snapshot/Definitions/Abstract.lean:23
/-- Stop uniformly before one of the first `m` accesses; inspect the static tree. -/noncomputable def snapshotMean (n : Nat) (p : Nat → ℝ) (t : Tree) (m : Nat) : ℝ :=  (∑ j ∈ Finset.range m, snapshotAt n p t j) / m
defSplay.probabilityEntropypropext · Classical.choice · Quot.soundAlgorithms/Splay/Snapshot/Definitions/Abstract.lean:27
/-- Shannon entropy in bits; zero-probability terms are zero. -/noncomputable def probabilityEntropy (n : Nat) (p : Nat → ℝ) : ℝ :=  ∑ x ∈ Finset.range n, p x * Real.logb 2 (1 / p x)
  • meanSearch n p t is the expected cost of one static search in t: one unit for the request plus the depth of the requested key. It uses (run t x).2, the splay rotation count, which equals the depth (Section 24.1). The leading 1 is the expectation of one unit only when the probabilities sum to one, which the theorem assumes.
  • snapshotAt n p t j is the expected meanSearch of the tree after j independent splay accesses from t. The recursion conditions on the first request: with probability p x it is x, and the remaining j accesses start from (run t x).1. This is the expectation over all njn^j request sequences, written as an iterated finite sum.
  • snapshotMean n p t m averages snapshotAt over j=0,…,m−1j = 0, \dots, m-1. The stopping time is uniform: the snapshot is taken just before one of the first m accesses, each with probability 1/m1/m.
  • probabilityEntropy is Shannon entropy in bits.
Reading the Lean

Two division-by-zero conventions matter here. In Lean, 1/0=01/0 = 0 and Mathlib’s log⁡20=0\log_2 0 = 0. So a zero-probability key contributes 0⋅log⁡2(1/0)=00 \cdot \log_2(1/0) = 0 to the entropy, the usual convention 0log⁡0=00 \log 0 = 0. And snapshotMean … 0 would be 0/0=00/0 = 0; the theorem excludes this with 0 < m. Probabilities are only read at ranks below n; values of p beyond the tree are irrelevant except for the hypothesis nonnegative, which quantifies over all indices.

Theorem (snapshot). Let pp be a probability distribution on the nn keys of a tree tt, and let m>0m > 0. Starting from tt, perform independent splay accesses drawn from pp, and freeze the tree just before one of the first mm accesses, chosen uniformly at random. In the frozen tree, the expected cost of one static search drawn from pp is at most 5+3H(p)+n(1+log⁡2n)/m5 + 3H(p) + n(1 + \log_2 n)/m, where H(p)H(p) is the entropy of pp in bits.

theoremSplay.Results.snapshotpropext · Classical.choice · Quot.soundAlgorithms/Splay/Snapshot/Abstract.lean:13
theorem snapshot (t : Tree) (p : Nat → ℝ) (nonnegative : ∀ i, 0 ≤ p i)    (normalized : ∑ i ∈ Finset.range t.size, p i = 1) (m : Nat) (positive : 0 < m) :    snapshotMean t.size p t m ≤ 5 + 3 * probabilityEntropy t.size p +      (t.size : ℝ) * (1 + Real.logb 2 t.size) / m :=  Splay.snapshot_bound t p nonnegative normalized m positive

The last term is the cost of an arbitrary starting tree, amortized over the window of m accesses. Keys of probability zero are allowed. The statement’s reading base contains no potential function: only the model, the splay algorithm and the finite-sum definitions above.

Proof sketch

The analysis uses the weights w(x)=p(x)+1/nw(x) = p(x) + 1/n, which are positive even where pp vanishes, and total W=2W = 2. Averaging the weighted access lemma over one random request gives E[depth+1]+E[Φ′]≤2+3∑xp(x)(log⁡2W−log⁡2w(x))+Φ\mathbb E[\text{depth} + 1] + \mathbb E[\Phi'] \le 2 + 3\sum_x p(x)(\log_2 W - \log_2 w(x)) + \Phi. Iterating this over j<mj < m telescopes the potential, which lies between nlog⁡2(1/n)n\log_2(1/n) and nlog⁡2W=nn \log_2 W = n. This gives the n(1+log⁡2n)/mn(1+\log_2 n)/m term. Finally w(x)≥p(x)w(x) \ge p(x), so ∑xp(x)(1−log⁡2w(x))≤1+H(p)\sum_x p(x)(1 - \log_2 w(x)) \le 1 + H(p), and 2+3(1+H)=5+3H2 + 3(1 + H) = 5 + 3H. See Algorithms/Splay/Snapshot.lean.

24.3.4 Sequential access

Accessing 0,1,…,n−10, 1, \dots, n-1 in order costs O(n)O(n) by the scanning theorem, from any initial shape. The statement uses only the splay algorithm and the cost of Chapter 5:

Theorem (sequential access). For every initial tree on nn keys, accessing the keys 0,1,…,n−10, 1, \dots, n-1 in order by splaying has total cost at most 14n14n. On the pointer machine of Chapter 7, the same scan, ending in exactly the splay tree, costs at most 40n40n.

theoremSplay.Results.scanningpropext · Classical.choice · Quot.soundAlgorithms/Splay/Scanning/Abstract.lean:14
/-- Accessing every key once in increasing order takes linear total cost. -/theorem scanning (t : Tree) :    algorithm.totalCost t (List.range t.size) ≤ 14 * t.size :=  Scanning.total_bound t
theoremSplay.Results.pointer_scanningpropext · Classical.choice · Quot.soundAlgorithms/Splay/Scanning/Abstract.lean:19
/-- The same scan has a linear-cost conventional pointer implementation,preserving the exact final splay tree. -/theorem pointer_scanning (t : Tree) :    ∃ k, k ≤ 40 * t.size ∧      Pointer.Execution t (List.range t.size) (algorithm.runFrom [] t (List.range t.size)).1 k :=  Scanning.pointer_bound t

The scan List.range t.size is every key once, in increasing order. The constants are deliberately generous. The README notes that the sharper 5.5n5.5n of Kakimura and Terai (2026) is not claimed.

24.3.4.1 The ghost marking

The proof needs bookkeeping that the algorithm never sees. During the scan, each tree has a simple global form: the current root (the last key accessed), with everything before it on its left, and a right spine of not-yet-accessed nodes. Each spine node has a left subtree that is partly restructured. The analysis marks those left subtrees:

inductiveSplay.Scanning.Markedno axiomsAlgorithms/Splay/Scanning/Definitions/Abstract.lean:9
/-- Analysis-only marking. A hole is an entirely unmarked subtree; a node ismarked red. The actual splay algorithm never stores these marks. -/inductive Marked where  | hole (tree : Tree)  | node (left right : Marked)
defSplay.Scanning.Marked.treeno axiomsAlgorithms/Splay/Scanning/Definitions/Abstract.lean:17
def tree : Marked → Tree  | .hole t => t  | .node l r => .node l.tree r.tree
defSplay.Scanning.Marked.rankno axiomsAlgorithms/Splay/Scanning/Definitions/Abstract.lean:21
/-- Number of red nodes on the right spine. -/def rank : Marked → Nat  | .hole _ => 0  | .node _ r => r.rank + 1
defSplay.Scanning.Marked.Validno axiomsAlgorithms/Splay/Scanning/Definitions/Abstract.lean:26
def Valid : Marked → Prop  | .hole _ => True  | .node l r => l.Valid ∧ r.Valid ∧ l.rank ≤ r.rank + 1

A Marked value is a tree in which a top part of red nodes (node) has been touched, and everything below the red part is an untouched subtree (hole). tree forgets the marks. rank is the number of red nodes on the right spine of a marked tree. Valid requires, at every red node, that the left child’s rank is at most the right child’s plus one.

defSplay.Scanning.Marked.alphano axiomsAlgorithms/Splay/Scanning/Definitions/Abstract.lean:30
def alpha (v : Nat) : Nat := if v = 0 then 5 else 3 - v
defSplay.Scanning.Marked.creditno axiomsAlgorithms/Splay/Scanning/Definitions/Abstract.lean:32
def credit (g h : Nat) : Nat := h * h + 2 * alpha (g - h)
defSplay.Scanning.Marked.potentialno axiomsAlgorithms/Splay/Scanning/Definitions/Abstract.lean:34
/-- Twice the red-node potential, plus a budget for first exposing each node.The right-spine (black) nodes are accounted for by a constant per request. -/def potential : Marked → Nat  | .hole t => 18 * t.size  | .node l r => l.potential + r.potential + credit (r.rank + 1) l.rank

The potential gives each red node a credit h2+2α(g−h)h^2 + 2\alpha(g-h), where hh is its left child’s rank and gg its own rank. The correction α(v)\alpha(v) is 55 for v=0v = 0 and 3−v3 - v otherwise; Lean’s truncated subtraction makes it 2,1,0,0,…2, 1, 0, 0, \dots for v=1,2,3,…v = 1, 2, 3, \dots. A hole holding ss untouched nodes carries 18s18s: a prepaid budget for marking those nodes red when the scan first reaches them. The docstring describes the total as twice the red-node potential plus this budget. The analysis doubles it so that every quantity stays a natural number, and the proof bounds 2R2R.

Proof sketch

Accessing rank 0 first costs fewer than nn rotations (Results.correct) and leaves a root with an empty left subtree. From then on, the next key is always the minimum of the right subtree. If the first spine node has an empty left subtree, the access is one rotation. Otherwise the left spine of that left subtree is painted red, paid from the hole budget. The red ancestors of the minimum are then consumed in pairs, which are the zig-zig steps, and the last one or two steps involve the spine node and the old root (consume_splay proves that this ghost pairing has exactly the shape splayAt produces). Each access satisfies 2k+Φ′≤Φ+62k + \Phi' \le \Phi + 6. Each middle pair pays for its two rotations out of the quadratic credit, by the arithmetic lemma pair_credit. Summing over the remaining n−1n-1 accesses, starting from an initial potential of at most 18n18n, gives at most 12n12n rotations after the first access, hence R≤13nR \le 13n and m+R≤14nm + R \le 14n. The pointer bound is m+3R≤n+39nm + 3R \le n + 39n. See Algorithms/Splay/Scanning/.

Reading the Lean

None of Marked, rank, credit or potential appears in the statement of scanning. Its reading base, checked by #check_bst_abstract, lists only the model, online algorithms, the pointer machine and the splay algorithm. To trust the theorem you do not need to understand the potential at all; it lives entirely in the proof.

The figure scans all keys from a chosen starting shape and plots the cumulative total cost against 14n14n. Starting from a left path, the first access alone costs n−1n-1 rotations, but the rest of the scan is cheap.