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 for each preference change is -competitive. Section 26.2 builds such an algorithm.
Fix a reference tree on keys and a sequence of requests. Serve 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 , the number of switches, where a node’s preference changes from one side to the other, is exactly Wilber’s interleave quantity of Chapter 17;
- the number of settings, meaning switches plus the first time each node receives a preference, is at most .
By Wilber’s bound, both are , where is the rotation count of the best offline execution.
The Lean statements
/-- 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 validModels.Rotation, Bounds.Interleave.Definitions, Algorithms.Tango.Definitions, Algorithms.Tango.Preferences/-- 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 xsModels.Rotation, Bounds.Interleave.Definitions, Algorithms.Tango.Definitions, Algorithms.Tango.PreferencesSplay trees are conjectured to be dynamically optimal, but the best proven competitive ratio for splaying is still , 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 -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 on the same keys. never changes and it is never stored as a search structure. It serves only as bookkeeping. Each node of 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 . Tango stores each preferred path as a small auxiliary BST, of size at most the height of . The actual BST is made of these auxiliary trees hanging off one another.
A request for changes the preferred child of some nodes on the reference path from the root to . Each change is repaired by a constant number of cuts and joins on auxiliary trees, at cost each. The total number of changes is essentially Wilber’s interleave quantity. The algorithm therefore pays 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 :
/-- 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 , 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 and a right subtree of size . Its height is at most , 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:
/-- 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 visits at most height t nodes.
Theorem (perfect trees). perfect h has keys and height .
/-- 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 downwardModels.Rotation, Bounds.Interleave.Definitions, Algorithms.Tango.Definitions, Algorithms.Tango.Preferencestheorem perfect_reference (h : Nat) : (perfect h).size = 2 ^ h - 1 ∧ height (perfect h) = h := ⟨perfect_size h, perfect_height h⟩Models.Rotation, Bounds.Interleave.Definitions, Algorithms.Tango.Definitions, Algorithms.Tango.Preferencespath_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 it reads .
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 splits its subtree into a left region, made of and its left subtree, and a right region, made of its right subtree. A request for 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 changes the preference of exactly those nodes on the reference search path to whose new region differs from their last one. The library counts these changes:
/-- 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 0changes 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 if the history is empty. The first observation of a node sets its preference and is not counted as a change. Otherwise it returns 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:
/-- 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]) xsThe 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 be a key of the reference tree . Appending to any history increases by exactly the number of switches that causes, changes t past x.
Theorem (switches are interleave). If every request in is a key of , then equals the total number of switches when is served from the empty history, changeCost t [] X.
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 validModels.Rotation, Bounds.Interleave.Definitions, Algorithms.Tango.Definitions, Algorithms.Tango.Preferences/-- 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 validModels.Rotation, Bounds.Interleave.Definitions, Algorithms.Tango.Definitions, Algorithms.Tango.Preferencesinterleave_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.
Chapter 17 proves that Wilber.interleave of any reference tree is at most for every offline execution with rotations on 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 , children and , leaves . Serve the requests .
| request | nodes whose preference is set for the first time | switches | changes |
|---|---|---|---|
| (left), (right), (left) | none | ||
| (left) | : left → right | ||
| none | : right → left | ||
| (left) | : right → left |
changeCost is . Computing interleave offline gives the same value. At the root, the regions of are left, right, left, left, with two alternations. At node , the requests fall right then left, giving one alternation. No other node alternates. Node ’s preference is set by the first request and then switched twice. Node is set once and never switched. For node , the request is itself, so its left child 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 alternations has runs:
/-- First setting plus subsequent changes of an observed region label. -/def runs (trace : List Bool) : Nat := match trace with | [] => 0 | _ :: _ => 1 + alternations trace/-- 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)/-- 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 on keys and every sequence , the number of preference settings is at most .
/-- 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 xsModels.Rotation, Bounds.Interleave.Definitions, Algorithms.Tango.Definitions, Algorithms.Tango.PreferencesThis is the source of the additive initialization term in the competitive theorem. On the example above, preferenceChanges is : three switches plus five first settings, for nodes . Indeed .
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:
/-- A component beginning at the current root, and the remaining components. -/abbrev PathDecomposition := List Nat × List (List Nat)def PathDecomposition.parts (d : PathDecomposition) : List (List Nat) := if d.1 = [] then d.2 else d.1 :: d.2A 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).
/-- 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)/-- The current preferred paths, with no empty components. -/def preferredPaths (reference : Tree) (past : List Nat) : List (List Nat) := (decomposePaths reference 0 past).partsAt 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 the paths are , , and . Before any request, all seven nodes are singleton paths. After the second request, , the root path is . It continues to although was never requested: node prefers its left region because itself was requested.
- A preferred path is a downward path of the reference tree, so by
Results.path_sizeit has at mostheight referencenodes. This bound is what makes the auxiliary trees of Section 26.2 small. - After a request for , every node on the reference search path to prefers the side containing , and prefers its left region. So the root’s preferred path passes through . 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:
/-- 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/-- 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 []/-- 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]) xsA 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 is .
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 (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.