Chapter 32Treaps
Chapter 12 states that every arborally satisfied point set can be executed by a binary search tree that touches exactly one node per point. The proof, due to Demaine, Harmon, Iacono, Kane and Pătraşcu (2009), is a data structure: a treap whose priorities are the times at which keys will next be touched. The converse, that the touched nodes of any rooted-region execution form an arborally satisfied set, rests on the mirror-image invariant, a heap of the times at which keys were last touched. This chapter presents the definitions these two arguments are built from, and how the proofs use them.
Together the two arguments prove the exact form of the equivalence, with no constant factors at all: a point set and a BST execution in the rooted-region model of Chapter 8 cost the same.
The last two sections leave the geometric setting. They state the classical facts about treaps for arbitrary distinct priorities, and define the random treaps that Lazy Finger Theorem 1 uses in Chapter 15, and that give the expected depths of random search trees in Chapter 22.
For every , every request sequence and every number , the following are equivalent:
- there is an arborally satisfied set of exactly points, with keys less than and times less than , that contains the point of every request;
- some BST on keys can serve in the rooted-region model, touching exactly nodes in total.
The initial tree is not fixed: the construction chooses it, and it needs the whole sequence in advance. In Lean, the point sets are Geometric.Offline solutions and the executions are RegionExecutions.
The Lean statement
/-- Exact point-count equivalence with rooted-subtree BST executions.The initial tree is free; the conversion is offline. -/theorem ass_iff_region_execution (n : Nat) (xs : List Nat) (cost : Nat) : (∃ E : Offline n xs, E.points.card = cost) ↔ ∃ s t, s.size = n ∧ RegionExecution s xs t cost := … offline_iff_regions n xs costApart from Geometric.Heap, which the general treap facts at the end of the chapter use, none of the definitions of the next five sections appears in a theorem statement of the reading interface. They live in Structures/Treap/Abstract.lean, Models/Region/Abstract.lean and Models/Region/View/Abstract.lean, and they are shown so that the proofs of Results.ass_iff_region_execution and Results.ass_to_pointers can be followed in the source. The regions and region executions they manipulate were defined in Chapter 8, and points, rows and arboral satisfaction in Chapter 9.
32.1 Treaps on ranks
A treap, introduced by Aragon and Seidel at FOCS 1989 (Seidel and Aragon 1996) and the same object as a Cartesian tree (Vuillemin 1980), is a binary search tree whose nodes also carry priorities, arranged in heap order: every node has priority at most that of each of its descendants. When priorities are distinct, the treap on a given key set is unique: its root is the key of minimum priority, and its two subtrees are the treaps of the keys on either side. On shapes, where keys are inorder ranks, heap order is a property of a shape and a priority function on ranks:
/-- A treap on consecutive inorder ranks. Each subtree root has minimumpriority in its interval. Equal priorities impose no extra tie-breaking rule. -/def Heap {α : Type} [LE α] (priority : Nat → α) : Tree → Nat → Prop | .nil, _ => True | .node l r, lo => (∀ x < l.size + 1 + r.size, priority (lo + l.size) ≤ priority (lo + x)) ∧ Heap priority l lo ∧ Heap priority r (lo + l.size + 1)Heap priority t lo reads the subtree t as holding the ranks lo, lo+1, …, lo + t.size - 1, as in Chapter 1. Its root lo + l.size must have priority at most that of every rank lo + x in the interval, not just its two children, and both subtrees must be heaps on their own intervals. On a heap the two formulations agree, and quantifying over the interval makes the invariant easy to restrict to a subtree, exactly like LabelledTree.Ordered in Chapter 4.
- The priority type
αonly needs≤. The library uses it withWithTop Natfor next touches and with the order dual ofWithBot Natfor last touches, below. - There is no tie-breaking rule. With equal priorities several shapes satisfy
Heap, and every statement that uses it holds for all of them. The construction needs this freedom: once a key is never touched again its priority is⊤, and many keys share it. - Every interval has a treap. The library proves it, for priorities in a linear order, by the textbook recursion: put a key of minimum priority at the root and recurse on both sides. The statement is
Results.exists_tree, below.
32.2 Priorities from the future
Fix an arborally satisfied point set and a time . The priority of a key is the first time, at or after , at which touches it:
/-- First touch at or after `time`; infinity means that the key is never touchedagain. These priorities depend on the future and are used only offline. -/def nextTouch (P : Finset Point) (time key : Nat) : WithTop Nat := ((P.filter fun p => p.1 = key ∧ time ≤ p.2).image Prod.snd).minThe value is the minimum of the times of the points in column key at or after time, in WithTop Nat, so a key with no such point gets ⊤, read “never again”. This priority depends on the future of the execution, and the construction is offline for that reason alone.
Here is the invariant of the construction: before row is served, the tree is a treap for nextTouch P t. Its first consequence needs no geometry at all. A key touched at time has priority exactly , the smallest value any key can have at time . If is touched at time , every ancestor of has priority at most , so it is touched at time as well. The keys of row are therefore closed under taking ancestors: they form a rooted connected region at the top of the tree. A row of the point set is a legal step of the rooted-region model of Chapter 8.
The proof reads this region off the tree by descending from the root while the visited key is touched on the current row. It is the definition Region.project in Models/Region/Defs.lean. Like the next three definitions of this chapter, it belongs to the proof, not to any theorem statement, so the book describes it without quoting its Lean. project P time t lo turns t into a Region. A node whose key is touched at time becomes a region node, and the first untouched key on each branch closes the descent: its whole subtree becomes a hole, kept intact. On any tree, project returns a region whose tree is t again. On a next-touch treap it selects the whole row: the internal lemma Region.project_keys states that the active keys of the projection are exactly the keys touched at time in the interval. This is where the descent’s “stop at the first untouched key” is justified: below an untouched key nothing is touched on this row.
32.3 Rearranging the touched region
After row , only the priorities of touched keys change. An untouched key has nextTouch P (t+1) x = nextTouch P t x, because its next touch was already after . Every hole of the region is therefore still a treap for the new priorities, and it is enough to rearrange the region itself. Inside the region, the target order is heap order among its own nodes, Region.ActiveHeap: ActiveHeap priority s lo asks that every region node have priority at most that of every active key below it, ignoring the holes entirely. Any region can be rearranged into this order without changing its fringe: the internal lemma Region.heapify (in Models/Region/Heapify.lean) produces a region u with Region.Same s u lo and ActiveHeap priority u lo. It brings an active key of minimum priority to the top and recurses on both sides, with the holes riding along in inorder. Planning the rearrangement is free in the model; only the touched nodes are charged.
Heap order among the active nodes is not yet a treap. A rearranged node may now sit directly above a hole, and its new priority must not exceed the priorities inside that hole. This is the one place where arboral satisfaction enters:
/-- No other point on the current row lies between `a` and `b`. -/def RowAdjacent (P : Finset Point) (time a b : Nat) : Prop := ∀ x, (x, time) ∈ P → min a b ≤ x → x ≤ max a b → x = aRowAdjacent P time a b says that no point of row time lies between a and b, except possibly at a itself. A hole of the region is a maximal interval of keys untouched at , and it hangs from one of the two touched keys that bound it. So every key of a hole is row-adjacent to its parent . The internal lemma adjacent_nextTouch (in Structures/Treap/Priorities.lean) then states:
If is arborally satisfied, , , and and are row-adjacent at time , then
nextTouch P (t+1) a ≤ nextTouch P (t+1) b.
The argument is short. Suppose is next touched at time . The rectangle spanned by and contains a third point of , and in an arborally satisfied set one can find such a point on one of the two sides through . The bottom side is row between and , which adjacency rules out. So the point is in column , at a time in , and is touched again no later than .
With this lemma, Region.restore (in Structures/Treap/Restore.lean) shows that a region in active heap order, whose holes are treaps and whose keys are exactly the row, is a treap for time . The invariant is restored, and the next row is again the top region of the tree.
Take a treap for nextTouch P 0 on the keys; this is the initial tree, and the construction chooses it. For each row : project the row, which contains the request, rearrange it into heap order for time , and continue. Each step is a RegionStep charging the size of the row, so the total charge is exactly the number of points of . This is the forward direction of Results.ass_iff_region_execution. Serving each region on the pointer machine instead, by two applications of the reshaping lemma Results.reshape, costs at most instructions per touched node, which is Results.ass_to_pointers.
The figure runs the construction on the GreedyASS solution (Section 25.1) of a request sequence you choose. The point set is drawn below the tree with the same horizontal axis, so each column of points sits under its key. Steps alternate between highlighting the touched region of the current row and rearranging it. The hanging subtrees never change; only the highlighted nodes move.
Step through the whole sequence and check that the highlighted region is always at the top of the tree, and that it contains every point of the current row. Then pick a key whose next touch is far away and follow it: it sinks below the keys that will be needed sooner. Switch the priority labels to “last touch” and check that the same trees are also ordered by the past, most recent on top. The next section explains why.
The figure’s JavaScript port breaks priority ties by the smaller key, which is one of the choices Heap allows. Its test suite checks every invariant above on the GreedyASS point sets computed by Lean: heap order before and after each row, project returning exactly the row, unchanged fringes, the adjacency inequality, and a total charge equal to the number of points.
32.4 Priorities from the past
The converse direction starts from an arbitrary execution of the rooted-region model and must show that the touched nodes, row by row, form an arborally satisfied set. There is no future to consult, only the history. The proof uses two definitions from Models/Region/View/Defs.lean. lastTouch P key is the latest time at which the history P touches key, in WithBot Nat, and ⊥ if it never has. HistoryHeap P t says that t is a max-heap of last touches, with the most recently touched keys on top. It is stated with Geometric.Heap by reversing the order: OrderDual.toDual turns “minimum of the dual” into “maximum”. Keys never touched have priority ⊥, the bottom of the original order, so they sink below every touched key.
The invariant is maintained by every rooted-region step, whatever rearrangement it chooses:
- Initially the history is empty, every key has priority
⊥, and every tree is a history heap. - A step touches a rooted region at the new time . Every key of the region now has last touch , the maximum, and the region is at the top of the tree. Its holes are untouched and keep their order. So any rearrangement of the region is again a history heap (
region_history_heap, inModels/Region/View/Preservation.lean).
The invariant gives arboral satisfaction one row at a time. Let be an old point and a point of the new row, with , so . The rooted region touched at time contains , so it also contains every ancestor of . The internal lemma between_ancestor finds a key of the region between and whose last touch is at least that of ; on the tree, is the lowest common ancestor of and , which lies between them in inorder and above in the heap. If , the point is a third point of the rectangle. If , then was last touched at some time in , and that point lies on the rectangle’s side. Pairs inside the new row are degenerate, and pairs of old points were handled before. This is region_ass, and iterating it along a RegionExecution gives the backward direction of Results.ass_iff_region_execution, with exactly one point per touched node.
The two invariants describe the same trees in the treap construction. Before row , the tree is a min-heap of next touches and, by the argument above, a max-heap of last touches. The figure’s “last touch” labels show the second order on the trees built for the first. Keys touched recently and keys needed soon are near the root, and the construction of the previous section is one particular way of keeping both.
32.5 Where these definitions sit
The treap construction is the only offline argument of the geometric chapters. Its priorities come from the future of the point set, so it converts a whole solution, never a request at a time. The online direction, in Section 25.2, cannot know next touches and replaces the treap by last-touch supernodes stored in the split trees of Chapter 33.
32.6 Treaps for arbitrary priorities
Everything so far used treaps for one kind of priority, the next touches. Three classical facts hold for priorities in any linear order. They are stated in Structures/Treap/Order/Abstract.lean and are used by the random treaps of the next section. All three read a tree on the ranks lo, lo+1, …, lo + n - 1, as Geometric.Heap does.
Theorem (existence). For every priority function into a linear order, every interval of ranks has a treap of size . Ties are allowed.
/-- Every finite inorder interval has a treap for priorities in any linearorder. In particular priorities need not be next-touch times. -/theorem exists_tree {α : Type} [LinearOrder α] (priority : Nat → α) (n lo : Nat) : ∃ t : Tree, t.size = n ∧ Heap priority t lo := heap_exists priority n loThe proof is the recursion of the first section: a key of minimum priority is the root, and both sides are built recursively. The priorities can be anything, not only next-touch times.
Theorem (uniqueness). If the priorities are distinct on the interval, two treaps of the same size on it are the same tree.
/-- Distinct priorities make that treap unique. -/theorem unique_shape {α : Type} [LinearOrder α] (priority : Nat → α) (t u : Tree) (lo : Nat) (size : t.size = u.size) (ht : Heap priority t lo) (hu : Heap priority u lo) (unique : Set.InjOn priority (Set.Ico lo (lo + t.size))) : t = u := heap_unique priority t u lo size ht hu uniqueDistinctness is needed only on the interval, Set.InjOn priority (Set.Ico lo (lo + t.size)). Keys outside it may share priorities.
Theorem (ancestors are interval minima). Let the priorities be distinct on the interval, and let and be two of its ranks. Then lies on the search path to exactly when has the smallest priority among all ranks between and , inclusive.
/-- The ancestor event is exactly an interval-minimum event. This deterministicidentity does not assume or assert a distribution on priorities. -/theorem ancestor_minimum {α : Type} [LinearOrder α] (priority : Nat → α) (t : Tree) (lo a x : Nat) (heap : Heap priority t lo) (unique : Set.InjOn priority (Set.Ico lo (lo + t.size))) (ha : lo ≤ a ∧ a < lo + t.size) (hx : lo ≤ x ∧ x < lo + t.size) : a ∈ t.searchPath lo x ↔ ∀ b, min a x ≤ b → b ≤ max a x → priority a ≤ priority b := heap_ancestor_iff priority t lo a x heap unique ha hxThe search path (Tree.searchPath) runs from the root to and includes both. So “on the search path to ” means “an ancestor of , or itself”, and for both sides hold trivially. The proof follows the root, which has the minimum priority of the whole interval. If the root is , both sides hold. If the root is , or lies strictly between and , both sides fail: is not on the path, and the root is a rank of the interval with a smaller priority than . Otherwise and lie in the same subtree, and the induction continues there. This is a deterministic identity, with no probability in it. It turns every ancestor event of a treap into an event about which key of an interval has the smallest priority.
32.7 Random treaps
Theorem 1 of the lazy finger paper (Bose et al. 2016) gives, for any positive weights, a randomized static tree in which, for every pair of keys , the expected cost of moving the lazy finger from to is within a constant factor of the weighted dynamic-finger charge of the pair. The library states it as Results.weighted_charge in Chapter 15. The random tree is a treap with random priorities, and this section defines the probability space. It lives in Structures/Treap/Random/Definitions/Abstract.lean and contains no measure theory: it is a finite weighted average over orders of the keys.
A random order replaces random priorities. The key listed first gets the smallest priority and becomes the root of the treap, and so on down the list.
/-- A sampled order contains every universe key exactly once. -/def IsOrder (s : Finset Nat) (xs : List Nat) : Prop := xs.Nodup ∧ xs.toFinset = sIsOrder s xs says that xs lists every key of the finite set s exactly once.
/-- Expectation over a random priority order on `s`: choose its next key withprobability proportional to its positive weight, remove it, and repeat.The sampled list runs from lowest to highest priority. This is an explicitfinite distribution; positivity is required by its probability theorems. -/noncomputable def average (w : Nat → ℝ) (s : Finset Nat) (f : List Nat → ℝ) : ℝ := if s = ∅ then f [] else ∑ x ∈ s.attach, w x.1 / (∑ k ∈ s, w k) * average w (s.erase x.1) (fun xs => f (x.1 :: xs))termination_by s.carddecreasing_by exact Finset.card_erase_lt_of_mem x.2average w s f is the expected value of f xs when the order xs of s is drawn as follows. The first key is chosen from s with probability proportional to its weight, . The rest of the order is drawn in the same way from the remaining keys. Written out, the order has probability
which is sampling without replacement proportional to weight (the Plackett–Luce distribution). With equal weights every order has probability . Equivalently, though the library never uses this, one may give the keys independent exponential priorities with rates and sort them increasingly.
To read a random treap off an order, use the position in the list as the priority, xs.idxOf. On a genuine order these positions are distinct (order_idxOf_injective), so by Results.unique_shape the order determines the treap. If T xs is a treap for xs.idxOf, then average w s (fun xs => g (T xs)) is the expectation of g over the random treap.
- The definition is total. The empty set gives
f [], and nothing in the definition requires positive weights. With nonpositive weights it is not an expectation. With total weight , Lean’s division by zero gives for every term. The probability statements all assume0 < w xon the set. - Under that hypothesis the proof files establish what an expectation should satisfy. The total probability is one (
average_const), and the average is linear (average_add,average_mul,average_sum). It depends only on the values offon genuine orders (average_congr,average_mono). exists_order_le_averageis the finite probabilistic method: some genuine order makesfat most its average. This turns the randomized tree into a deterministic one.
/-- First key of `s` in an order; `none` if the order contains no such key. -/def firstIn (s : Finset Nat) : List Nat → Option Nat | [] => none | x :: xs => if x ∈ s then some x else firstIn s xs/-- Probability that `a` has minimum priority in `s`, when priorities aresampled over the whole universe `u`. -/noncomputable def firstProbability (w : Nat → ℝ) (u s : Finset Nat) (a : Nat) : ℝ := average w u (fun xs => if firstIn s xs = some a then 1 else 0)firstIn s xs is the first key of s in the list xs, that is, the key of s with the smallest priority, or none if xs contains no key of s. firstProbability w u s a is the probability that a comes first among s when the whole universe u is ordered at random. The basic lemma is firstProbability_eq (in Random/Minimum.lean):
If the weights are positive on
u,s ⊆ uanda ∈ s, thenfirstProbability w u s a.
The keys outside s do not bias which key of s comes first. Combined with Results.ancestor_minimum, this gives the ancestor probabilities of a random treap. Let be the total weight of the ranks between and inclusive:
- lies on the search path to with probability (
exists_random_treap, inRandom/Tree.lean); - lies on the search paths to both and with probability (
common_ancestor_probability).
The lazy-finger distance between and counts the ancestors of and of that are not common ancestors. Summing these probabilities over gives the exact expected distance Results.expected_distance, and bounding the sums gives Results.weighted_charge. Both are in Chapter 15.
The two theorems of Chapter 15 assert that some family of trees T : List Nat → Tree, each of size , has the stated average. They do not say that T xs is a treap. The treap is the witness built in the proof, by exists_random_treap. Their statements depend on this chapter only through average, the distribution over orders.