Chapter 24 · Splay trees · Section 24.2The amortized analysis
A single splay can be slow: an access at depth costs rotations. Sleator and Tarjan’s insight is that such an access also roughly halves the depth of every node on its path, so expensive accesses pay for later cheap ones. They make this precise with a potential function and one lemma, the Access Lemma. A whole family of bounds then follows by choosing weights:
- amortized cost per access (balance);
- within a constant factor of the best static tree for the sequence (static optimality);
- cheap accesses near any fixed key (static finger);
- cheap accesses to recently used keys (working set).
These are the headline results of the 1985 paper, and all four hold for the same algorithm, which never sees the weights. This section proves them with explicit constants. In all four, is an arbitrary initial tree on keys, is a sequence of keys of , and is the number of rotations splaying performs while serving . The total cost counts one unit per request plus one per rotation (Chapter 5).
Every splay is a legal root access by rotations, fewer than of them. Serving any sequence of requests by splaying, from any initial tree on keys, has total cost
In Lean, correct certifies one splay as an Access, and balance bounds totalCost of Splay.algorithm, the online algorithm that splays each request in turn.
The Lean statements
/-- Splay exposes exactly the requested rank using a legal rotation trace.Its rotation count is the depth of that rank, hence less than the number of nodes. -/theorem correct (t : Tree) (x : Nat) (valid : x < t.size) : Access t (run t x).1 x (run t x).2 ∧ (run t x).2 < t.size := … run_correct t x validModels.Rotation, Models.Online, Models.Pointer.Machine, Algorithms.Splay.Algorithm, Algorithms.Splay.Online, Bounds.WorkingSet/-- Balance theorem, including requests and the arbitrary initial shape. -/theorem balance (t : Tree) (xs : List Nat) (valid : ∀ x ∈ xs, x < t.size) : (algorithm.totalCost t xs : ℝ) ≤ (xs.length : ℝ) * (2 + 3 * Real.logb 2 t.size) + (t.size : ℝ) * Real.logb 2 t.size := … Splay.balance t xs validModels.Rotation, Models.Online, Models.Pointer.Machine, Algorithms.Splay.Algorithm, Algorithms.Splay.OnlineLet key be requested times. There are constants and such that for every initial tree on keys and every sequence of requests,
The sum is times the entropy of the access frequencies. The bracket is a lower bound for static trees: for every BST on the same keys, serving the sequence by plain searches in costs , which is at least a third of the bracket. So splaying, which never learns the frequencies, costs at most times as much as the best static tree for the sequence, plus a startup term.
In Lean, staticOptimality is the property HasStaticOptimalityBound of Splay.algorithm, and entropy_lower_bound is the comparison with every static tree, whose search cost is StaticTree.cost.
The Lean statements
theorem staticOptimality : HasStaticOptimalityBound algorithm := … Splay.hasWorkingSetBound.staticOptimality algorithmtheorem entropy_lower_bound (t : Tree) (xs : List Nat) (valid : ∀ x ∈ xs, x < t.size) : Bounds.staticCost t.size xs ≤ 3 * (StaticTree.cost t xs : ℝ) := … entropy_le_cost t xs validModels.Rotation, Models.Online, Bounds.WorkingSet, Bounds, Bounds.StaticTree.Definitions, Models.Pointer.MachineThere are constants and such that for every initial tree on keys, every fixed key (the finger) and every sequence of requests,
Keys are ranks, so is the number of keys between the request and the finger. The finger is used only in the analysis: the algorithm is plain splaying.
In Lean, staticFinger is the property HasStaticFingerBound of Splay.algorithm; the sum is Bounds.fingerCost.
The Lean statement
theorem staticFinger : HasStaticFingerBound algorithm := … Splay.hasWorkingSetBound.staticFinger algorithmModels.Rotation, Models.Online, Models.Pointer.Machine, Algorithms.Splay.Algorithm, Algorithms.Splay.Online, BoundsFor each request , let be one plus the number of distinct keys requested since the previous request to , or if was not requested before. For every initial tree on keys and every sequence of requests, the number of rotations is at most
A key that was used recently is cheap to access again, however large the tree. The sum charges at least per request, so adding the requests changes only the constant.
In Lean, is workingSetNumber and the sum is workingSetSum; Splay.algorithm.cost counts rotations only.
The Lean statement
theorem workingSet (t : Tree) (xs : List Nat) (valid : ∀ x ∈ xs, x < t.size) : algorithm.cost t xs ≤ 10 * workingSetSum t.size [] xs + 6 * t.size * (1 + t.size.log2) := … Splay.workingSet_bound t xs validModels.Rotation, Models.Online, Models.Pointer.Machine, Algorithms.Splay.Algorithm, Algorithms.Splay.Online, Bounds.WorkingSet24.2.1 Weights and potential
Sleator and Tarjan (1985) analyse splaying with a potential function. Each item gets a fixed positive weight . The size of a node is the total weight of its subtree, its rank is , and the potential of a tree is the sum of the ranks of its nodes. The Access Lemma bounds the amortized cost of one splay. Their Theorems 1–5 then follow by choosing the weights. The rest of this section shows the formal versions of the potential, the lemma and the five theorems. The bounds themselves (working set, entropy, finger) are defined in Chapter 14.
/-- Positive analysis weights are indexed by implicit inorder rank. -/def mass (w : Nat → ℝ) : Tree → Nat → ℝ | .nil, _ => 0 | .node l r, lo => mass w l lo + w (lo + l.size) + mass w r (lo + l.size + 1)/-- Sum of the binary logarithms of all nonempty subtree masses. -/noncomputable def potential (w : Nat → ℝ) : Tree → Nat → ℝ | .nil, _ => 0 | .node l r, lo => potential w l lo + potential w r (lo + l.size + 1) + Real.logb 2 (mass w (.node l r) lo)The weights are a function w : Nat → ℝ on ranks. Because a subtree does not know its own keys, both functions carry the offset lo of the subtree’s smallest key and update it exactly as labelFrom does (Chapter 1). The root of node l r is rank lo + l.size, so mass adds w (lo + l.size) between the masses of the two subtrees. mass w t 0 is the total weight of the tree. mass is the paper’s , and potential is , summed over nonempty subtrees only, so nil contributes neither weight nor a term.
potentialisnoncomputableonly because ofReal.logb. Nothing in it is chosen classically.- The weights are ghost data.
Splay.runtakes no weight argument, and every theorem below quantifies over weights only in its analysis, so the same algorithm satisfies all of them simultaneously. - The mass of a subtree depends only on the interval of keys it holds, not on its shape. Rotations therefore preserve the total weight and change only the masses of the rotated nodes. The library proves this as
mass_eq_sum. - With unit weights
fun _ => 1,massisTree.sizeand is .
24.2.2 The access lemma
Theorem (access lemma). Fix positive weights . Let be a tree of total weight , and let splaying the rank take rotations and produce . Then the amortized cost is bounded:
where is the initial weight of ’s subtree. Since , the same holds with replaced by .
/-- Weighted access lemma, using the accessed node's own weight. -/theorem access_lemma (w : Nat → ℝ) (positive : ∀ i, 0 < w i) (t : Tree) (x : Nat) (valid : x < t.size) : ((run t x).2 : ℝ) + potential w (run t x).1 0 - potential w t 0 ≤ 3 * (Real.logb 2 (mass w t 0) - Real.logb 2 (w x)) + 1 := Splay.access_lemma w positive t x validModels.Rotation, Models.Online, Models.Pointer.Machine, Algorithms.Splay.Algorithm, Algorithms.Splay.Potential/-- Stronger original form: the denominator is the initial subtree mass of the accessed node, not merely its own weight. -/theorem access_lemma_subtree (w : Nat → ℝ) (positive : ∀ i, 0 < w i) (t : Tree) (x : Nat) (valid : x < t.size) : ((run t x).2 : ℝ) + potential w (run t x).1 0 - potential w t 0 ≤ 3 * (Real.logb 2 (mass w t 0) - Real.logb 2 (mass w (locate t x).focus (Pointer.offset (locate t x).context))) + 1 := Splay.access_lemma_subtree w positive t x validModels.Rotation, Models.Online, Models.Pointer.Machine, Algorithms.Splay.Algorithm, Algorithms.Splay.PotentialIn Lean, is mass w t 0. access_lemma_subtree takes to be the initial mass of ’s subtree. It writes that as mass w (locate t x).focus (offset (locate t x).context): the focus is the subtree rooted at , and the offset is the rank of its smallest key. This is exactly Lemma 1 of the paper, . access_lemma weakens to the weight of itself, which is the only form the theorems below need.
- The hypothesis
positive : ∀ i, 0 < w iasks for positive weights at every natural number, though only ranks belowt.sizeaffect the statement. This costs nothing, since any positive weights on the keys extend to all ofNat. Positivity is needed becauseReal.logb 2 0 = 0in Mathlib: with a zero weight, would silently become . - The paper counts the time of a splay as its number of rotations, or if there are none. Here is exactly the number of rotations, possibly . The additive pays for a final zig.
- Both terms are evaluated with the same weights. Changing weights between accesses, as in the working-set proof, is a separate argument.
The proof is the paper’s. Three lemmas bound the amortized cost of the local steps: a zig costs at most , and a zig-zig or zig-zag at most (zig_left, zigzig_left, zigzag_left and their mirror images). A rotation inside the context leaves the mass of every strict ancestor unchanged, so it changes no other term of . The induction follows splayAt, and the bounds telescope.
The figure below runs the same transcription of run as in Section 24.1 with unit weights. It tracks , and at the end checks both inequalities on the actual run.
24.2.3 Balance (Theorem 1)
Theorem (balance). For every initial tree on keys and every sequence of valid requests, splaying has total cost .
/-- Balance theorem, including requests and the arbitrary initial shape. -/theorem balance (t : Tree) (xs : List Nat) (valid : ∀ x ∈ xs, x < t.size) : (algorithm.totalCost t xs : ℝ) ≤ (xs.length : ℝ) * (2 + 3 * Real.logb 2 t.size) + (t.size : ℝ) * Real.logb 2 t.size := Splay.balance t xs validModels.Rotation, Models.Online, Models.Pointer.Machine, Algorithms.Splay.Algorithm, Algorithms.Splay.OnlineThe paper’s Theorem 1 states . The left side is totalCost, so the request count is included (Chapter 5). The logarithms are real, Real.logb 2 t.size, not floors. When both sides are , since a valid request sequence on the empty tree is empty.
The proof uses unit weights. Then and , so each access has amortized rotation cost at most . Every subtree has mass at least , so , and initially . Summing over the sequence and adding gives the bound.
24.2.4 Static optimality (Theorem 2)
Theorem 2 of the paper states that if every item is accessed at least once, the total access time is , where is the number of accesses to . The library has three versions.
Theorem (static optimality, every key requested). If every key of the initial tree is requested at least once, then .
theorem staticOptimality_all_accessed (t : Tree) (xs : List Nat) (valid : ∀ x ∈ xs, x < t.size) (covers : ∀ x < t.size, x ∈ xs) : (algorithm.totalCost t xs : ℝ) ≤ 4 * Bounds.staticCost t.size xs := Splay.staticOptimality_all_accessed t xs valid coversThis is the paper’s statement with explicit constants: staticCost, which is , with no startup term. The hypothesis covers : ∀ x < t.size, x ∈ xs is exactly “every item is accessed”. The proof takes , so . The access lemma gives amortized cost . The potential drop over the whole sequence is at most , which is at most because every . Adding for the requests gives staticCost.
Theorem (static optimality). There are constants and such that for every initial tree on keys and every valid sequence, .
theorem staticOptimality : HasStaticOptimalityBound algorithm := Splay.hasWorkingSetBound.staticOptimality algorithmWithout covers, unused keys still sit in the tree, and some startup allowance is needed. HasStaticOptimalityBound (Chapter 14) has uniform but unspecified constants and an allowance. This theorem is not proved from the access lemma directly: it is the algorithm-independent implication “working set ⇒ static optimality” of Chapter 14, applied to splay's working-set bound.
Theorem (static optimality against a fixed tree). If every key is requested, then for every tree on the same keys, splaying from any initial tree has total cost .
/-- The paper's comparison-tree formulation, with no startup when every key occurs. -/theorem staticOptimality_fixedTree (t u : Tree) (xs : List Nat) (same : t.size = u.size) (valid : ∀ x ∈ xs, x < t.size) (covers : ∀ x < t.size, x ∈ xs) : (algorithm.totalCost t xs : ℝ) ≤ 12 * (StaticTree.cost u xs : ℝ) := Bridge.staticOptimality_fixedTree t u xs same valid coversThis is the comparison-tree reading of static optimality: splay, starting from any tree t, costs at most times what the best fixed BST u on the same keys would cost to serve xs by plain searches. StaticTree.cost counts one unit per request plus the depth of each requested key (Chapter 14). The constant is : staticOptimality_all_accessed contributes the , and the prefix-code bound entropy_lower_bound, which says staticCost ≤ 3 · StaticTree.cost u xs for every tree u, contributes the .
Both _all_accessed forms need covers. If some key is never requested, they say nothing. The general staticOptimality still applies, with an additive startup term and unspecified constants.
24.2.5 Static finger (Theorem 3)
Theorem (static finger). There are constants and such that for every initial tree on keys, every finger and every valid sequence, . If every key is requested, then for every natural number , with no startup term.
theorem staticFinger : HasStaticFingerBound algorithm := Splay.hasWorkingSetBound.staticFinger algorithmModels.Rotation, Models.Online, Models.Pointer.Machine, Algorithms.Splay.Algorithm, Algorithms.Splay.Online, Bounds/-- When every key occurs, the startup allowance can be omitted. -/theorem staticFinger_all_accessed (t : Tree) (xs : List Nat) (f : Nat) (valid : ∀ x ∈ xs, x < t.size) (covers : ∀ x < t.size, x ∈ xs) : (algorithm.totalCost t xs : ℝ) ≤ 12 * Bounds.fingerCost f xs := Bridge.staticFinger_all_accessed t xs f valid coversModels.Rotation, Models.Online, Models.Pointer.Machine, Algorithms.Splay.Algorithm, Algorithms.Splay.Online, BoundsTheorem 3 of the paper bounds the total time by for any fixed item . fingerCost f xs is . The distance is Nat.dist, the absolute difference of ranks, which matches the paper because its items are numbered in symmetric order. staticFinger is again the generic implication from working set (through static optimality). staticFinger_all_accessed removes the startup term when every key is accessed. Its constant comes from staticCost n xs ≤ 3 · fingerCost f xs (Bounds.static_le_finger), proved with the weights , whose total is at most .
In staticFinger_all_accessed the finger f is an arbitrary natural number. There is no hypothesis f < t.size, so the statement is slightly stronger than the paper’s. HasStaticFingerBound quantifies only over f < t.size.
24.2.6 Working set (Theorem 4)
Theorem (working set). For every initial tree on keys and every valid sequence, , where is the working-set number of request . In particular, splaying has the working-set property HasWorkingSetBound.
theorem workingSet (t : Tree) (xs : List Nat) (valid : ∀ x ∈ xs, x < t.size) : algorithm.cost t xs ≤ 10 * workingSetSum t.size [] xs + 6 * t.size * (1 + t.size.log2) := Splay.workingSet_bound t xs validModels.Rotation, Models.Online, Models.Pointer.Machine, Algorithms.Splay.Algorithm, Algorithms.Splay.Online, Bounds.WorkingSettheorem hasWorkingSetBound : HasWorkingSetBound algorithm := Splay.hasWorkingSetBoundModels.Rotation, Models.Online, Models.Pointer.Machine, Algorithms.Splay.Algorithm, Algorithms.Splay.Online, Bounds.WorkingSetTheorem 4 of the paper bounds the total time by , where counts the distinct items accessed since the previous access to . The formal version bounds rotations:
$$
where workingSetSum charges per request. The working-set number of a repeated access is the paper’s . A first access is charged , which is at least the paper’s value; the total extra charge is , within the startup term (Chapter 14 gives the exact conventions). Because workingSetSum charges at least per request, adding the requests costs at most one more unit per term. workingSet_totalCost_iff (Chapter 14) makes this precise for the property HasWorkingSetBound.
The proof follows the paper and changes the weights after every access. Before request , list the keys by recency: most recently accessed first, never-accessed keys after them in increasing order (Recency.recent). A key at 1-based position gets weight (Recency.weight). The total weight is at most for every order, so the access lemma bounds the amortized cost of accessing the key at position by (Recency.access_bound). After the access, moves to the front of the list. Its weight rises to , every other weight weakly falls, and the total is unchanged. Since is now the root, this cannot increase (Recency.touch_potential). Finally workingSetNumber: they are equal on a repeated access, and on a first access. For any order, lies between and , and this width is the term.
Theorem (working set on the pointer machine). For every initial tree and every valid sequence, there is a pointer-machine execution that ends in exactly the splayed tree and costs at most .
/-- Working set in the conventional pointer-and-rotation cost model. -/theorem pointer_workingSet (t : Tree) (xs : List Nat) (valid : ∀ x ∈ xs, x < t.size) : ∃ k, k ≤ 31 * workingSetSum t.size [] xs + 18 * t.size * (1 + t.size.log2) ∧ Pointer.Execution t xs (algorithm.runFrom [] t xs).1 k := Bridge.pointer_workingSet t xs validModels.Rotation, Models.Online, Models.Pointer.Machine, Algorithms.Splay.Algorithm, Algorithms.Splay.Online, Bounds.WorkingSetThe same bound in the conventional pointer model: the pointer implementation costs at most , and workingSetSum, so and .
24.2.7 The unified theorem (Theorem 5)
Theorem 5 of the paper charges each access the smallest of its three logarithmic costs: frequency, finger distance and working set. The charge unifiedCharge and its sum unifiedSum are sequence functions, defined with the other benchmarks in Section 14.7. The frequencies there come from the whole sequence, but only the analysis sees them; the algorithm is still Splay.run.
Theorem (unified bound, fixed finger). For every initial tree on keys, every natural number and every valid sequence, , where is the smallest of the frequency, finger and working-set charges of request .
theorem unified (t : Tree) (xs : List Nat) (f : Nat) (valid : ∀ x ∈ xs, x < t.size) : (algorithm.totalCost t xs : ℝ) ≤ 11 * unifiedSum t.size f xs [] xs + 8 * (t.size : ℝ) * (1 + (t.size.log2 : ℝ)) := Splay.unified_bound t xs f validModels.Rotation, Models.Online, Models.Pointer.Machine, Algorithms.Splay.Algorithm, Algorithms.Splay.Online, Bounds.Unified, Bounds.WorkingSetAs for the static finger theorem, there is no f < t.size hypothesis. The minimum is taken per access, so this is not merely the minimum of the three earlier theorems. The proof uses the sum of three weights: the recency weight , which changes after each access as in the working-set proof, plus two fixed weights, and . The total weight is at most , so . Each of the three weights is at most the combined weight, so the amortized cost of an access is at most unifiedCharge. Every charge is at least , which absorbs the requests into the constant .
This is the 1985 fixed-finger unified theorem. It is not the later unified bound of Iacono (2001), in which the finger distance is measured to recently accessed keys. Whether splay trees satisfy that bound is open, and the library makes no claim about it.
24.2.8 Measured cost against the bounds
The figure runs the transcription of splay on a request sequence and plots its cumulative cost against the bound of a chosen theorem. Each point applies the theorem to the first requests from the same initial tree. For the static-optimality bound, the panel checks the covers hypothesis and says when it fails.
Switch to Balance with sequential scans. The measured cost stays far below , because sequential access is linear (Section 24.3). Then try one key repeated under Working set: after the first access the key stays at the root, each request costs rotations, and the bound grows by per request. The theorems give worst-case guarantees with generous constants, not estimates of typical cost.
All the bounds of this section are amortized: a single access can cost rotations. Chapter 30 builds one deamortized splay program that keeps the scanning, balance, working-set, static-optimality and static-finger bounds up to constant factors, and serves every access in time in the worst case.