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

Chapter 5Online algorithms and cost

An Execution describes every legal way to serve a sequence: it is an offline object that knows the whole sequence in advance. A BST algorithm must decide what to do with each request when that request arrives. This chapter defines online algorithms in the rotation model, their two cost measures, and dynamic optimality. Chapter 7 shows that any such algorithm can be run online on a conventional pointer machine, with constant overhead.

The chapter has no main theorem of its own. It fixes the yardstick for Part IV. The definition of an online algorithm, Algorithm, is what “there is a BST algorithm that…” means in later statements. Its cost, Algorithm.cost or Algorithm.totalCost, is what their bounds measure. And dynamic optimality is the property those bounds approximate. The one theorem shown here, that online runs are offline executions, says the comparison is fair.

5.1 Online algorithms

structureAlgorithmno axiomsModels/Online/Abstract.lean:9
/-- An online rule sees only past requests, the current tree and current request.For each existing rank, it returns a tree and a certified rotation count. -/structure Algorithm where  step : List Nat → Tree → Nat → Tree × Nat  correct : ∀ past t x, x < t.size →    Access t (step past t x).1 x (step past t x).2

An Algorithm is a function together with a certificate.

  • step past t x receives the requests served so far (past, oldest first), the current tree t and the current request x. It returns the next tree and a rotation count. It receives nothing about future requests, and this is the only sense in which the algorithm is online.
  • correct certifies that whenever x is an existing rank, the returned pair is a legal root access: x ends at the root, and the returned count is the exact length of some rotation sequence from t to the new tree.
Reading the Lean
  • The cost cannot be under-reported. Access requires a rotation sequence of exactly the returned length, so the count is at least the rotation distance between the two trees. An algorithm could report more than it needs to (rotating back and forth), but never less.
  • No persistent state except the tree, but full history. There is no separate memory field. Any auxiliary state an algorithm might keep, such as counters, preferred children or timestamps, is a function of the request history, which step receives in full. Recomputing it costs nothing, since computation is uncharged: only rotations count. The interface is therefore more permissive than a pointer machine with O(1)O(1) words per node, which is the right direction for lower bounds and for definitions of optimality. Chapter 13 defines the stricter model, with bounded state and charged computation. Splaying (Section 24.1) ignores past entirely.
  • Invalid requests are outside the contract. For x ≥ t.size, step may return anything and correct says nothing. Every theorem about runs carries the hypothesis ∀ x ∈ xs, x < t.size.

Running an algorithm threads the tree through the sequence and adds the counts:

defAlgorithm.runFromno axiomsModels/Online/Abstract.lean:16
def Algorithm.runFrom (a : Algorithm) (past : List Nat) (t : Tree) :    List Nat → Tree × Nat  | [] => (t, 0)  | x :: xs =>      let (u, k) := a.step past t x      let (v, m) := a.runFrom (past ++ [x]) u xs      (v, k + m)
defAlgorithm.costno axiomsModels/Online/Abstract.lean:24
def Algorithm.cost (a : Algorithm) (t : Tree) (xs : List Nat) : Nat :=  (a.runFrom [] t xs).2

runFrom past t xs serves xs starting from history past. Each request is appended to the history after it is served (past ++ [x]), so the step for the jj-th request sees exactly the requests before it. cost starts with an empty history and keeps only the total number of rotations.

The simplest instance is moveToRootAlgorithm: it ignores the history and rotates the requested key up one level at a time, the witness used in Chapter 3. It opens Part IV in Chapter 23. Splaying (Section 24.1) is the main example.

A run of an algorithm on valid requests is one of the executions of Chapter 3. Online algorithms are therefore a special case of offline executions, and their cost is at least the offline optimum.

Theorem (online runs are executions). Let AA be an online algorithm, tt a tree, and XX a sequence of valid requests for tt. Running AA on XX from tt, after any history, is an execution of XX from tt whose cost is exactly the number of rotations AA reports.

theoremAlgorithm.executionpropext · Quot.soundModels/Rotation/Existence/Abstract.lean:25
/-- The online interface really produces legal executions on valid inputs. -/theorem Algorithm.execution (a : Algorithm) (past : List Nat) (t : Tree) (xs : List Nat)    (valid : ∀ x ∈ xs, x < t.size) :    Execution t xs (a.runFrom past t xs).1 (a.runFrom past t xs).2 :=  AccessBridge.run_execution a past t xs valid
Statement reads only Models/Rotation/Existence/Abstract.lean and its imports

The proof is an induction on xs that applies correct at every step. Sizes are preserved, so validity with respect to the initial tree remains validity at every later step.

5.2 Two cost measures

Algorithm.cost counts rotations only. The conventional cost of a BST algorithm charges each request at least one unit, for the comparison at the node that holds the key:

defAlgorithm.totalCostno axiomsModels/Online/Abstract.lean:32
/-- Conventional cost: one unit per request, plus rotations. -/def Algorithm.totalCost (a : Algorithm) (t : Tree) (xs : List Nat) : Nat :=  xs.length + a.cost t xs

We write RR for a.cost t xs, mm for xs.length and T=m+RT = m + R for a.totalCost t xs. The two measures differ in an essential way. A request for the current root costs 00 rotations, so a sequence of mm such requests has R=0R = 0 and T=mT = m. A bound of the form R≤C⋅f+DR \le C \cdot f + D therefore cannot be obtained from a bound on TT when ff can be smaller than mm. The bounds in Chapter 14 charge every request at least one unit, so for them the two measures are interchangeable (workingSet_totalCost_iff).

5.3 Dynamic optimality

Sleator and Tarjan (1985) conjectured that splay trees are dynamically optimal: on every sequence, their cost is within a constant factor of the best offline BST algorithm, up to an additive term that depends only on nn. The library states both versions of this property, one for each cost measure.

defDynamicallyOptimalno axiomsModels/Online/Abstract.lean:27
/-- Compare against every legal offline execution from the same initial tree. -/def DynamicallyOptimal (a : Algorithm) : Prop :=  ∃ C D : Nat, ∀ t xs u k, Execution t xs u k →    a.cost t xs ≤ C * k + D * t.size
defTotallyDynamicallyOptimalno axiomsModels/Online/Abstract.lean:36
/-- Conventional competitiveness; constants are uniform in size and sequence. -/def TotallyDynamicallyOptimal (a : Algorithm) : Prop :=  ∃ C D : Nat, ∀ t xs u k, Execution t xs u k →    a.totalCost t xs ≤ C * (xs.length + k) + D * t.size

Read the quantifiers in order. There exist constants C,DC, D; then for every initial tree t, every sequence xs and every offline execution of xs from t with any cost k, the algorithm’s cost on xs from t is at most C k+D nC\,k + D\,n, where nn = t.size.

Reading the Lean
  • Comparison against every execution, hence against the optimum. Quantifying over all executions Execution t xs u k is equivalent to comparing with the least such k, so the definition never needs to compute the offline optimum. The final tree u of the offline strategy is unconstrained.
  • Same initial tree. The offline strategy starts from the same t as the algorithm. The additive term is linear in nn, as in the usual statement of the conjecture. By Geometry.reset, allowing the offline strategy to choose its own initial tree would change its cost by at most 2n2n, so this choice does not matter.
  • Uniform constants. CC and DD are fixed before the tree and the sequence are chosen. In particular, they cannot depend on nn.
  • Invalid sequences are vacuous. If some request is out of range there is no Execution at all (execution_exists_iff), so the condition holds trivially.
  • DynamicallyOptimal compares rotation counts R≤C k+D nR \le C\,k + D\,n, while TotallyDynamicallyOptimal compares total costs T≤C(m+k)+D nT \le C(m + k) + D\,n. The total-cost version is the conventional notion of dynamic optimality, and it is the one that transfers to the pointer machine (Section 7.6).

The rotation-only notion implies the conventional one.

Theorem. Every dynamically optimal algorithm is totally dynamically optimal.

theoremDynamicallyOptimal.totalpropext · Quot.soundBounds/Normalization/Abstract.lean:25
/-- Rotation-only competitiveness implies conventional total-cost competitiveness.The converse is deliberately not asserted: requests can have zero rotations. -/theorem DynamicallyOptimal.total (a : Algorithm) (h : DynamicallyOptimal a) :    TotallyDynamicallyOptimal a :=  BoundsBridge.total_dynamic a h
Statement reads only Bounds/Normalization/Abstract.lean and its imports

The proof takes the constants (C+1,D)(C+1, D): add mm to both sides. The converse is deliberately not claimed. It holds only if no totally dynamically optimal algorithm exists, which is the open question itself. Suppose a is totally dynamically optimal, and let a' behave like a but, on every request, first rotate a child of the root up and back down. Then a' costs at most T+2m≤3TT + 2m \le 3T, so it is still totally dynamically optimal. But on mm requests for the root of a tree with at least two nodes, a' performs at least 2m2m rotations, while the offline execution that does nothing performs 00. No bound 2m≤C⋅0+D n2m \le C \cdot 0 + D\,n holds for all mm, so a' is not DynamicallyOptimal.

Not claimed for splay

Neither DynamicallyOptimal nor TotallyDynamicallyOptimal is proved for any algorithm in the library. The dynamic optimality conjecture is open. The theorems that mention it, such as the pointer-machine transfer of Section 7.6, are conditional: if an algorithm satisfies the property, then some consequence follows. Chapter 17 proves Wilber’s lower bound on the offline optimum, and Section 26.2 uses it to show that Tango trees are O(log⁡log⁡n)O(\log \log n)-competitive, the best ratio known.