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 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 from any initial tree. The library proves versions of all four. The two headline results are the dictionary bound and the scanning theorem:
Consider any sequence of 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 keys, and initially holds keys. Then the total cost is at most
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
/-- 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 executionFor every initial tree on keys, accessing the keys in increasing order by splaying costs at most in total, counting one unit per request plus one per rotation. The first access alone may take 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
/-- 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 tModels.Rotation, Models.Online, Models.Pointer.Machine, Algorithms.Splay.Algorithm, Algorithms.Splay.OnlineEach 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 , and an operation’s effect on keys is a statement about how ranks are renumbered. A gap is the position between ranks and , as in Chapter 1.
structure SplitResult where left : Tree right : Tree cost : Nat deriving DecidableEq, Repr/-- 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 , 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 of t becomes rank 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.
/-- 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).
/-- 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)/-- 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.
- 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.sizeforsplit,x ≥ t.sizefordelete) are outside every theorem below, which all assume validity.
The size lemmas confirm the renumbering.
Theorem (sizes). For valid arguments on a tree with keys, splitting at gap gives trees with and keys, joining gives keys, insertion adds one key and deletion removes one. A split at is a certified splay access to rank , followed by cutting the root’s right edge (split_spec).
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/-- 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 positivetheorem join_size (l r : Tree) : (join l r).1.size = l.size + r.size := Updates.join_size l rtheorem insert_size (t : Tree) (k : Nat) (valid : k ≤ t.size) : (insert t k).1.size = t.size + 1 := Updates.insert_size t k validtheorem delete_size (t : Tree) (x : Nat) (valid : x < t.size) : (delete t x).1.size = t.size - 1 := Updates.delete_size t x valid24.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.
/-- Number of stored keys across the forest. -/def forestSize (ts : List Tree) : Nat := (ts.map Tree.size).sum/-- 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 nStep 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:
framecarries an unrelated treeaalong unchanged, without changing the cost orn. Repeated use lets an operation act on any trees of a larger forest while the rest is untouched, and those untouched trees contribute nothing ton.rearrangelets 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.
/-- `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)/-- 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 operations during which the forest never holds more than keys, starting from a forest with keys in total. Its total cost is at most . If the forest starts empty, the total cost is at most , where is the number of keys in the trees that operation involves.
/-- 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/-- 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 emptyThe 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. :
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 , after which the root’s rank grows from to , giving in total.
Insertion is a split plus a new root, giving .
Deletion is an access plus a join, giving . With the unit charge, every case is at most . The initial potential is at most 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 as usual, but restructures only if the search path is long. The library fixes positive weights and the threshold that makes the access lemma pay for itself:
/-- 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)/-- 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 , twice the amortized bound of the access lemma, with = mass w t 0. Otherwise it returns the tree unchanged at cost zero. conditionalRun sums these costs over a request sequence.
- 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
noncomputableand decides the threshold classically. - is the total weight of the current tree. Weights are indexed by rank and rotations preserve ranks, so is the same for every tree reached.
- The returned number counts restructuring rotations only. A short search that does not splay still walks to ; it is not a zero-cost root access, and the conditional variant is not an
Algorithmin the sense of Chapter 5, because the tree it leaves need not have at the root. Its search cost is accounted for separately in the pointer model:Splay.conditionalStep_pointershows that each conditional step is served by a pointer search of cost at most .
Theorem (long splays). Fix positive weights , and let be the total weight of the keys. For every initial tree and every sequence of valid requests, conditional splaying performs at most restructuring rotations in total. With unit weights, this is at most .
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 validtheorem 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 validThe 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 is at least twice the access lemma’s charge , so , i.e. . When no splay happens, both sides are zero. Summing telescopes to . Every subtree’s mass lies between the weight of its root and , so the total drop is at most .
24.3.3 The snapshot theorem
Suppose requests are independent and key is requested with probability . 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:
/-- 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/-- 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/-- 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/-- 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 tis the expected cost of one static search int: 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 leading1is the expectation of one unit only when the probabilities sum to one, which the theorem assumes.snapshotAt n p t jis the expectedmeanSearchof the tree afterjindependent splay accesses fromt. The recursion conditions on the first request: with probabilityp xit isx, and the remainingjaccesses start from(run t x).1. This is the expectation over all request sequences, written as an iterated finite sum.snapshotMean n p t maveragessnapshotAtover . The stopping time is uniform: the snapshot is taken just before one of the firstmaccesses, each with probability .probabilityEntropyis Shannon entropy in bits.
Two division-by-zero conventions matter here. In Lean, and Mathlib’s . So a zero-probability key contributes to the entropy, the usual convention . And snapshotMean … 0 would be ; 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 be a probability distribution on the keys of a tree , and let . Starting from , perform independent splay accesses drawn from , and freeze the tree just before one of the first accesses, chosen uniformly at random. In the frozen tree, the expected cost of one static search drawn from is at most , where is the entropy of in bits.
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 positiveModels.Rotation, Models.Online, Models.Pointer.Machine, Algorithms.Splay.Algorithm, Algorithms.Splay.Snapshot.DefinitionsThe 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 , which are positive even where vanishes, and total . Averaging the weighted access lemma over one random request gives
.
Iterating this over telescopes the potential, which lies between and . This gives the term. Finally , so , and . See Algorithms/Splay/Snapshot.lean.
24.3.4 Sequential access
Accessing in order costs 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 keys, accessing the keys in order by splaying has total cost at most . On the pointer machine of Chapter 7, the same scan, ending in exactly the splay tree, costs at most .
/-- 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 tModels.Rotation, Models.Online, Models.Pointer.Machine, Algorithms.Splay.Algorithm, Algorithms.Splay.Online/-- 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 tModels.Rotation, Models.Online, Models.Pointer.Machine, Algorithms.Splay.Algorithm, Algorithms.Splay.OnlineThe scan List.range t.size is every key once, in increasing order. The constants are deliberately generous. The README notes that the sharper 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:
/-- 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)def tree : Marked → Tree | .hole t => t | .node l r => .node l.tree r.tree/-- Number of red nodes on the right spine. -/def rank : Marked → Nat | .hole _ => 0 | .node _ r => r.rank + 1def Valid : Marked → Prop | .hole _ => True | .node l r => l.Valid ∧ r.Valid ∧ l.rank ≤ r.rank + 1A 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.
def alpha (v : Nat) : Nat := if v = 0 then 5 else 3 - vdef credit (g h : Nat) : Nat := h * h + 2 * alpha (g - h)/-- 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.rankThe potential gives each red node a credit , where is its left child’s rank and its own rank. The correction is for and otherwise; Lean’s truncated subtraction makes it for . A hole holding untouched nodes carries : 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 .
Proof sketch
Accessing rank 0 first costs fewer than 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 . Each middle pair pays for its two rotations out of the quadratic credit, by the arithmetic lemma pair_credit. Summing over the remaining accesses, starting from an initial potential of at most , gives at most rotations after the first access, hence and . The pointer bound is . See Algorithms/Splay/Scanning/.
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 . Starting from a left path, the first access alone costs rotations, but the rest of the scan is cheap.