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

Chapter 26 · Tango trees · Section 26.1Preferred paths

This section proves the counting identity behind Tango trees. Fix a balanced reference tree on the keys and serve requests one at a time. Each node of the reference tree prefers the side of its subtree where the most recent request in that subtree fell. The number of times these preferences change turns out to be exactly Wilber’s interleave quantity from Chapter 17, which is a lower bound on the cost of every BST execution. So an algorithm that pays O(log⁡log⁡n)O(\log\log n) for each preference change is O(log⁡log⁡n)O(\log\log n)-competitive. Section 26.2 builds such an algorithm.

Main result
Preference changes are Wilber’s interleave bound

Fix a reference tree PP on nn keys and a sequence XX of requests. Serve XX one request at a time. After each request, every node on the search path to the requested key prefers the side of its subtree that holds that key: the left side if the key is the node itself or lies in its left subtree, the right side otherwise. Then:

  • if every request is a key of PP, the number of switches, where a node’s preference changes from one side to the other, is exactly Wilber’s interleave quantity IBP(X)\mathrm{IB}_P(X) of Chapter 17;
  • the number of settings, meaning switches plus the first time each node receives a preference, is at most IBP(X)+n\mathrm{IB}_P(X) + n.

By Wilber’s bound, both are O(OPT+∣X∣)+nO(\mathrm{OPT} + |X|) + n, where OPT\mathrm{OPT} is the rotation count of the best offline execution.

The Lean statements
theoremTango.Results.interleave_switchespropext · Quot.soundAlgorithms/Tango/Abstract.lean:24
/-- The interleave quantity counts exactly the switches of preferred regions.First observations initialize a region and are not switches. -/theorem interleave_switches (t : Tree) (xs : List Nat)    (valid : ∀ x ∈ xs, x < t.size) : Wilber.interleave t xs = changeCost t [] xs := … by  simpa only [List.nil_append, Wilber.interleave_nil, Nat.zero_add] using changeCost_eq t [] xs valid
theoremTango.Results.preference_settingspropext · Quot.soundAlgorithms/Tango/Abstract.lean:34
/-- Initial preference settings add at most one charge per reference key. -/theorem preference_settings (t : Tree) (xs : List Nat) :    preferenceChanges t xs ≤ Wilber.interleave t xs + t.size := … preferenceChanges_bound t xs
12 definitions in 3 chapters · reading list

Splay trees are conjectured to be dynamically optimal, but the best proven competitive ratio for splaying is still O(log⁡n)O(\log n), the trivial bound that any balanced tree achieves. Tango trees (Demaine et al. 2007), introduced at FOCS 2004, were the first online BST algorithm proved O(log⁡log⁡n)O(\log \log n)-competitive. Their key idea is to make an algorithm whose cost can be charged directly to a lower bound. They use Wilber’s interleave bound from Chapter 17, which is at most a constant times the cost of any offline execution.

The design uses a fixed balanced reference tree PP on the same keys. PP never changes and it is never stored as a search structure. It serves only as bookkeeping. Each node of PP has a preferred child: the child on the side where the most recent request in the node’s subtree went. Following preferred children from a node gives a downward preferred path, and these paths partition the nodes of PP. Tango stores each preferred path as a small auxiliary BST, of size at most the height h≈log⁡2nh \approx \log_2 n of PP. The actual BST is made of these auxiliary trees hanging off one another.

A request for xx changes the preferred child of some nodes on the reference path from the root to xx. Each change is repaired by a constant number of cuts and joins on auxiliary trees, at cost O(log⁡h)=O(log⁡log⁡n)O(\log h) = O(\log\log n) each. The total number of changes is essentially Wilber’s interleave quantity. The algorithm therefore pays O(log⁡log⁡n)O(\log\log n) per unit of a lower bound on the optimum.

This section covers the reference-tree side of the argument. Everything here is a function of the reference tree and the request sequence alone; no BST is restructured. Section 26.2 builds the actual data structure on top of it.

The box above states the result; checking it needs only Wilber’s definitions and the two counts defined here. The section proceeds in order. Section 26.1.1 defines the reference trees. Section 26.1.2 defines preferences and proves that switches are the interleave quantity. Section 26.1.3 adds the first settings. The last two sections describe the preferred paths themselves and the log of preference updates, which is what the data structure of Section 26.2 replays. The definitions are in Algorithms/Tango/Definitions/Abstract.lean, Reference/, Preferences/ and Paths/. The theorems are in Algorithms/Tango/Abstract.lean.

26.1.1 The reference tree

Only two properties of the reference tree matter: it has the right number of keys, and it is shallow. The library measures depth by Tree.height (Chapter 1), which counts the nodes on a longest root-to-leaf path, not the edges. So a preferred path, which is a set of nodes on one downward path, never has more nodes than the height.

Two families of reference trees are provided. Perfect trees are the classical choice when n=2h−1n = 2^h - 1:

defTango.perfectno axiomsAlgorithms/Tango/Definitions/Abstract.lean:34
/-- A perfect reference tree, useful when the key count is `2^h - 1`. -/def perfect : Nat → Tree  | 0 => .nil  | h + 1 => .node (perfect h) (perfect h)

For every other nn, the library uses the balanced tree Tree.balanced of Chapter 19, which splits the remaining keys as evenly as possible, with the larger half on the left. For example, balanced 7 is perfect 3, and balanced 6 has a left subtree of size 33 and a right subtree of size 22. Its height is at most ⌊log⁡2n⌋+1\lfloor\log_2 n\rfloor + 1, which is the bound used in the final theorem of Section 26.2. Tango’s own names for these two definitions, Tango.height and Tango.balanced, are aliases.

A preferred path is a path in the ordinary sense. It starts at some node and repeatedly steps to a child:

inductiveTango.DownwardPathno axiomsAlgorithms/Tango/Definitions/Abstract.lean:39
/-- A preferred path is an ordinary downward path in the reference tree. -/inductive DownwardPath : Tree → List Bool → Prop  | stop (l r : Tree) : DownwardPath (.node l r) []  | left {l r : Tree} {path : List Bool} :      DownwardPath l path → DownwardPath (.node l r) (true :: path)  | right {l r : Tree} {path : List Bool} :      DownwardPath r path → DownwardPath (.node l r) (false :: path)

DownwardPath t path says that the list of directions path (true for left, false for right) can be followed from the root of t without falling off the tree. The path visits path.length + 1 nodes, counting the start. Two facts are used later.

Theorem (paths are short). A downward path of a tree tt visits at most height t nodes.

Theorem (perfect trees). perfect h has 2h−12^h - 1 keys and height hh.

theoremTango.Results.path_sizepropext · Quot.soundAlgorithms/Tango/Abstract.lean:38
/-- An auxiliary tree representing a preferred path has at most `height t` keys. -/theorem path_size {t : Tree} {path : List Bool} (downward : DownwardPath t path) :    path.length + 1 ≤ height t := downward_length downward
theoremTango.Results.perfect_referencepropext · Quot.soundAlgorithms/Tango/Abstract.lean:42
theorem perfect_reference (h : Nat) :    (perfect h).size = 2 ^ h - 1 ∧ height (perfect h) = h :=  ⟨perfect_size h, perfect_height h⟩

path_size is what bounds the size of every auxiliary tree by height t. Every preferred path is a downward path that starts at some node of the reference tree, so it is a downward path of that node’s subtree, whose height is at most height t. perfect_reference is stated with Lean’s truncated subtraction; for h=0h = 0 it reads 0=1−10 = 1 - 1.

26.1.2 Preferences and switches

The preference of a reference node is the region its subtree’s most recent request fell in. The regions are those of Wilber’s bound (Wilber.regions). A node vv splits its subtree into a left region, made of vv and its left subtree, and a right region, made of its right subtree. A request for vv itself therefore makes the left child preferred. This is the convention of Demaine, Harmon, Iacono and Pătraşcu, and it is fixed once and for all in Wilber’s definitions.

Serving a request for xx changes the preference of exactly those nodes on the reference search path to xx whose new region differs from their last one. The library counts these changes:

defTango.changesno axiomsAlgorithms/Tango/Definitions/Abstract.lean:13
/-- Actual preference switches on the reference search path for one request. -/def changes : Tree → List Nat → Nat → Nat  | .nil, _, _ => 0  | .node l r, past, x =>      if x < l.size + 1 + r.size then        Wilber.switch (Wilber.regions l.size (l.size + 1 + r.size) past) (x ≤ l.size) +        if x < l.size then changes l (Wilber.leftRequests l.size past) x        else if x = l.size then 0        else changes r (Wilber.rightRequests l.size past) (x - l.size - 1)      else 0

changes t past x walks down the reference search path for x. At each node it compares the node’s region history (Wilber.regions … past, the regions of the past requests that fell in this subtree, oldest first) with the region of x, using Wilber.switch. switch returns 00 if the history is empty. The first observation of a node sets its preference and is not counted as a change. Otherwise it returns 11 exactly when the last observed region differs from the new one. The recursion then continues into the subtree containing x, with requests translated to local ranks by Wilber.leftRequests and Wilber.rightRequests, exactly as in the definition of Wilber.interleave. It stops at x itself.

Summed over a sequence, with each request appended to the history after it is served:

defTango.changeCostno axiomsAlgorithms/Tango/Definitions/Abstract.lean:24
/-- Total changes made while processing a sequence online. -/def changeCost (t : Tree) : List Nat → List Nat → Nat  | _, [] => 0  | past, x :: xs => changes t past x + changeCost t (past ++ [x]) xs

The two theorems below say that this online count is Wilber’s quantity. Wilber’s definition is offline: for each reference node, it takes the subsequence of requests in the node’s subtree and counts how often consecutive ones alternate between the two regions. changeCost instead processes requests one at a time and charges each request for the switches it causes. The two agree, step by step and in total.

Theorem (one step). Let xx be a key of the reference tree tt. Appending xx to any history increases IBt\mathrm{IB}_t by exactly the number of switches that xx causes, changes t past x.

Theorem (switches are interleave). If every request in XX is a key of tt, then IBt(X)\mathrm{IB}_t(X) equals the total number of switches when XX is served from the empty history, changeCost t [] X.

theoremTango.Results.interleave_incrementpropext · Quot.soundAlgorithms/Tango/Abstract.lean:30
theorem interleave_increment (t : Tree) (past : List Nat) (x : Nat) (valid : x < t.size) :    Wilber.interleave t (past ++ [x]) = Wilber.interleave t past + changes t past x :=  interleave_step t past x valid
theoremTango.Results.interleave_switchespropext · Quot.soundAlgorithms/Tango/Abstract.lean:24
/-- The interleave quantity counts exactly the switches of preferred regions.First observations initialize a region and are not switches. -/theorem interleave_switches (t : Tree) (xs : List Nat)    (valid : ∀ x ∈ xs, x < t.size) : Wilber.interleave t xs = changeCost t [] xs := by  simpa only [List.nil_append, Wilber.interleave_nil, Nat.zero_add] using changeCost_eq t [] xs valid

interleave_increment is the one-step identity: appending a valid request x to the history increases the interleave quantity by exactly changes t past x. Only the nodes on the search path to x see a new observation, and each gains an alternation exactly when its region switches. interleave_switches follows by induction from the empty history. Both theorems assume the requests are valid ranks of the reference tree. An out-of-range request falls in no region and is ignored by both sides, so the hypothesis is only needed for the step-by-step bookkeeping.

Why this matters

Chapter 17 proves that Wilber.interleave of any reference tree is at most 4R+2m4R + 2m for every offline execution with RR rotations on mm requests (Results.rotation_lower_bound). By interleave_switches, the total number of preference switches that Tango has to repair is bounded by the cost of the optimal offline execution, up to a constant. The whole competitive analysis rests on this identity.

26.1.2.1 A worked example

Take the perfect reference tree on seven keys, perfect 3: root 33, children 11 and 55, leaves 0,2,4,60, 2, 4, 6. Serve the requests 2,5,3,02, 5, 3, 0.

request nodes whose preference is set for the first time switches changes
22 33 (left), 11 (right), 22 (left) none 00
55 55 (left) 33: left → right 11
33 none 33: right → left 11
00 00 (left) 11: right → left 11

changeCost is 33. Computing interleave offline gives the same value. At the root, the regions of 2,5,3,02, 5, 3, 0 are left, right, left, left, with two alternations. At node 11, the requests 2,02, 0 fall right then left, giving one alternation. No other node alternates. Node 33’s preference is set by the first request and then switched twice. Node 55 is set once and never switched. For node 55, the request 55 is itself, so its left child 44 becomes preferred.

26.1.3 Counting first settings

Tango has to pay for first settings as well as switches, because both change the preferred-path structure. The library counts the runs of a region trace, meaning the maximal blocks of equal consecutive labels. A nonempty trace with aa alternations has a+1a + 1 runs:

defTango.runsno axiomsAlgorithms/Tango/Preferences/Abstract.lean:9
/-- First setting plus subsequent changes of an observed region label. -/def runs (trace : List Bool) : Nat :=  match trace with  | [] => 0  | _ :: _ => 1 + alternations trace
defTango.preferenceChangesno axiomsAlgorithms/Tango/Preferences/Abstract.lean:23
/-- All preferred-region settings, including the first setting of each node. -/def preferenceChanges : Tree → List Nat → Nat  | .nil, _ => 0  | .node l r, xs => runs (regions l.size (l.size + 1 + r.size) xs) +      preferenceChanges l (leftRequests l.size xs) + preferenceChanges r (rightRequests l.size xs)
defTango.initializationsno axiomsAlgorithms/Tango/Preferences/Abstract.lean:15
/-- Number of reference nodes whose regions have been observed at least once.Counting leaf labels is harmless and gives an upper bound for child settings. -/def initializations : Tree → List Nat → Nat  | .nil, _ => 0  | .node l r, xs =>      (if regions l.size (l.size + 1 + r.size) xs = [] then 0 else 1) +      initializations l (leftRequests l.size xs) + initializations r (rightRequests l.size xs)

preferenceChanges t xs is the total number of preference settings over the whole sequence: first settings plus switches, summed over all nodes. It has the same recursive structure as Wilber.interleave, with runs in place of alternations. initializations counts the nodes whose region trace is nonempty, which are the nodes that ever receive a preference. As its docstring notes, this includes leaves, whose preferred “child” is an empty subtree. That only overcounts.

The difference between the two counts is at most one first setting per node.

Theorem (settings). For every reference tree tt on nn keys and every sequence XX, the number of preference settings is at most IBt(X)+n\mathrm{IB}_t(X) + n.

theoremTango.Results.preference_settingspropext · Quot.soundAlgorithms/Tango/Abstract.lean:34
/-- Initial preference settings add at most one charge per reference key. -/theorem preference_settings (t : Tree) (xs : List Nat) :    preferenceChanges t xs ≤ Wilber.interleave t xs + t.size := preferenceChanges_bound t xs

This is the source of the additive O(nlog⁡log⁡n)O(n \log\log n) initialization term in the competitive theorem. On the example above, preferenceChanges is 88: three switches plus five first settings, for nodes 3,1,2,5,03, 1, 2, 5, 0. Indeed 8≤3+78 \le 3 + 7.

Reading the Lean

preference_settings has no validity hypothesis. Out-of-range requests fall in no region, so they contribute to neither side.

26.1.4 The preferred-path partition

At any moment the preferences determine a partition of the reference nodes into downward paths. Start at a node whose parent does not prefer it, and follow preferred children until reaching a node with no preference (never observed) or an empty preferred subtree. The library computes the partition bottom-up:

defTango.PathDecompositionno axiomsAlgorithms/Tango/Paths/Abstract.lean:10
/-- A component beginning at the current root, and the remaining components. -/abbrev PathDecomposition := List Nat × List (List Nat)
defTango.PathDecomposition.partsno axiomsAlgorithms/Tango/Paths/Abstract.lean:13
def PathDecomposition.parts (d : PathDecomposition) : List (List Nat) :=  if d.1 = [] then d.2 else d.1 :: d.2

A PathDecomposition of a subtree is a pair. The first component is the path that starts at the subtree’s root and is still open, because a preferred path may continue upward into the parent. The second component lists the paths that are already closed. parts returns all the paths, omitting the open one when it is empty (the empty subtree).

defTango.decomposePathsno axiomsAlgorithms/Tango/Paths/Abstract.lean:16
/-- Compute the preferred-path partition of the fixed reference tree from pastrequests. Each path lists its keys from shallowest to deepest in the reference. -/def decomposePaths : Tree → Nat → List Nat → PathDecomposition  | .nil, _, _ => ([], [])  | .node l r, lo, past =>      let left := decomposePaths l lo past      let right := decomposePaths r (lo + l.size + 1) past      let root := lo + l.size      match (labels lo root (lo + l.size + 1 + r.size) past).getLast? with      | none => ([root], left.parts ++ right.parts)      | some true => (root :: left.1, left.2 ++ right.parts)      | some false => (root :: right.1, left.parts ++ right.2)
defTango.preferredPathsno axiomsAlgorithms/Tango/Paths/Abstract.lean:29
/-- The current preferred paths, with no empty components. -/def preferredPaths (reference : Tree) (past : List Nat) : List (List Nat) :=  (decomposePaths reference 0 past).parts

At a node root = lo + l.size (keys are absolute ranks here, so lo is the subtree’s offset, as in Chapter 1), decomposePaths reads the node’s most recent region with Wilber.labels, which works in absolute ranks.

  • No observation yet. The node is a path by itself, and both children’s paths are closed.
  • Left preferred. The node is prepended to the left child’s open path. The right child’s paths are all closed.
  • Right preferred. The same, with left and right exchanged.

Each path is listed from its shallowest node to its deepest. preferredPaths reference past is the resulting partition, with the root’s path first.

On the example, after the requests 2,5,3,02, 5, 3, 0 the paths are [3,1,0][3, 1, 0], [5,4][5, 4], [2][2] and [6][6]. Before any request, all seven nodes are singleton paths. After the second request, 55, the root path is [3,5,4][3, 5, 4]. It continues to 44 although 44 was never requested: node 55 prefers its left region because 55 itself was requested.

Reading the Lean
  • A preferred path is a downward path of the reference tree, so by Results.path_size it has at most height reference nodes. This bound is what makes the auxiliary trees of Section 26.2 small.
  • After a request for xx, every node on the reference search path to xx prefers the side containing xx, and xx prefers its left region. So the root’s preferred path passes through xx. Tango relies on this: the requested key is always in the topmost auxiliary tree after the preferences are updated.

26.1.5 The update log

The data structure does not recompute the partition from scratch. It replays, for each request, the list of preference settings that the request causes:

structureTango.PreferenceUpdateno axiomsAlgorithms/Tango/Preferences/Updates/Abstract.lean:9
/-- One changed preference at an absolute reference key. `none` is its firstsetting; an existing equal preference produces no log entry. -/structure PreferenceUpdate where  key : Nat  previous : Option Bool  next : Bool  deriving DecidableEq, Repr
defTango.preferenceUpdatesno axiomsAlgorithms/Tango/Preferences/Updates/Abstract.lean:17
/-- Changes for one request, in reference-root-to-request order. Requests andhistory use local ranks; `lo` translates the recorded node keys to global ranks. -/def preferenceUpdates : Tree → Nat → List Nat → Nat → List PreferenceUpdate  | .nil, _, _, _ => []  | .node l r, lo, past, x =>      if x < l.size + 1 + r.size then        let previous := (regions l.size (l.size + 1 + r.size) past).getLast?        let next := decide (x ≤ l.size)        (if previous = some next then [] else [⟨lo + l.size, previous, next⟩]) ++          if x < l.size then preferenceUpdates l lo (leftRequests l.size past) x          else if x = l.size then []          else preferenceUpdates r (lo + l.size + 1) (rightRequests l.size past) (x - l.size - 1)      else []
defTango.preferenceLogno axiomsAlgorithms/Tango/Preferences/Updates/Abstract.lean:31
/-- The causally generated preference-change log for a request sequence. -/def preferenceLog (t : Tree) : List Nat → List Nat → List PreferenceUpdate  | _, [] => []  | past, x :: xs => preferenceUpdates t 0 past x ++ preferenceLog t (past ++ [x]) xs

A PreferenceUpdate names a reference node by its absolute rank, key. It records the node’s previous preference, previous, which is none for a first setting, and the new one, next, with true meaning left. preferenceUpdates t lo past x lists the updates for one request, from the reference root down toward x, skipping nodes whose preference does not change. It is changes with the count replaced by a log of what changed and with first settings included. preferenceLog concatenates the logs of a whole sequence, served online.

In the example, the log for the request 55 is ⟨3,left,right⟩,⟨5,none,left⟩\langle 3, \text{left}, \text{right}\rangle, \langle 5, \text{none}, \text{left}\rangle.

The BST of Section 26.2 repairs each entry of the log with at most one cut and one join of auxiliary trees: a first setting only joins, and a switch cuts one subpath and joins another. Summed over a sequence, the log has one entry per preference setting, so its length is bounded by preferenceChanges, and hence by the interleave quantity plus nn (Results.preference_settings). The library proves this bound for the log internally, as part of the competitive theorem. On the reading surface, the per-request bound of Section 26.2 is stated in terms of (preferenceUpdates reference 0 past x).length.