Module contents
Lesson 9 of 33Advanced 105 min

Treaps, skip lists and splay trees

Balance without color rules through randomized treaps and skip lists or self-adjusting splay trees. Prove the access lemma, examine working-set and dynamic-optimality results, and introduce persistence by path copying.

After this lesson you can

  • Implement a treap with split and merge and prove logarithmic expected depth.
  • Analyze skip-list height and space with high probability.
  • Prove the splay-tree access lemma using the potential method.
  • Explain working-set and static-finger properties and the dynamic optimality conjecture.
  • Implement a persistent tree by path copying and measure its overhead.

Before you start

Motivation: balancing without special cases

A red–black tree guarantees worst-case height O(log⁡n)\bigO(\log n), at the cost of fragile logic: insertion has three cases plus their mirrors, deletion has more, and an error may gradually worsen height or corrupt the tree much later instead of breaking the program immediately. Each insertion can also recolor an entire path to the root, making it difficult to share the tree across threads.

This lesson presents two ways to balance without color rules, both more useful than they first appear:

  • Randomize. Treaps and skip lists flip coins on insertion. Structure shape depends on those choices rather than key arrival order, so no insertion order, however bad, produces a degenerate tree except with negligible probability. Analysis follows randomized quicksort, and implementation fits in twenty lines with primitives split and merge, also providing concatenation, set union and sequences with reversed ranges.
  • Self-adjust. A splay tree stores no balance information. Each key access raises it to the root using specific rotations. An individual operation may cost Θ(n)\Theta(n), but any sequence of mm operations costs O((m+n)log⁡n)\bigO((m + n)\log n), and the tree learns access patterns: if a few keys dominate accesses or accesses have temporal locality, cost falls below log⁡n\log n without instruction. Whether any search tree, even knowing the sequence beforehand, can serve some sequence more than a constant factor better is a major open problem in data structures.

Finally, a third idea changes the question: instead of modifying the tree, create a new version sharing almost everything with the old one. This is persistence, underlying git, immutable maps in functional languages and some transactional databases.

What follows uses the preceding lesson’s binary search tree and rotation vocabulary. Recall that a rotation raises a node one level and lowers its parent, preserves in-order traversal and costs O(1)\bigO(1).

Treaps: a search tree that is also a heap

It is not obvious that both orders can hold: search order governs horizontally (left and right), heap order vertically (up and down). The first result says it is possible and leaves no freedom.

Proof

Induct on pair count. With zero pairs the empty tree is unique. With n≥1n \ge 1, heap order forces the minimum-priority pair, say (kr,pr)(k_r, p_r), to be the root; distinct priorities make it unique. Search order places exactly the pairs with keys less than krk_r in the left subtree and greater keys in the right. Each is a treap with fewer pairs, determined by induction. Conversely, root (kr,pr)(k_r, p_r) with those treaps as children satisfies both orders, so the treap exists.

∎

The proof is also an algorithm, with a consequence underlying the analysis. Insert keys into an ordinary BST without rotations in increasing priority order: the first is the root, each lands in its proper subtree, and the result satisfies both orders. By uniqueness, it is the treap.

With continuous iid priorities, their order is a uniform permutation and shape depends only on it. The second sentence distinguishes treaps from ordinary BSTs: a random BST is good when data arrives randomly; a treap is good always, because it supplies the randomness. The sole assumption is that whoever chooses keys cannot see priorities.

To insert, descend as in any BST and attach the new node as a leaf. Search order holds, but heap order may fail on the parent edge. Repair with rotations: while the node’s priority is below its parent’s, rotate it upward. Each rotation preserves search order and moves the violation one level up, like heap sift-up. To delete, reverse the process: rotate the node down, always with the lower-priority child, until it is a leaf, then remove it.

InteractiveThe treap as a random-priority heap
50203085721518824172636985279923513566391704659
  • darker: lower priority (closer to the root)
  • nodes moving in this step
  • edge violating heap order
  • selected for deletion
Treap with keys in search-tree order and priorities (the small number) in min-heap order. Insert a key and watch the rotations; click a node to delete it.
Priority of the new key
53
Keys nn12
Height4
Average depth2.25
Expected average (random)2.72
Rotations (last operation)·
Heap ordersatisfied
Each node shows its key and, underneath, priority; darker means lower priority and closer to the root. Insert a key: it enters as a leaf (the red dashed edge marks a heap-order violation) and rises one rotation per step until its parent has lower priority. Click a node and delete it to see the reverse. Compare modes: with increasing priorities each new key stays a leaf and the treap is an unbalanced BST, so «Vaciar e insertar en orden» produces a height-14 path; random priorities give logarithmic height for the same keys and insertion order. The expected-depth readout uses this section's formula.

How many rotations does insertion cost? In the worst case, as many as its depth. On average fewer than two, with an elegant argument: each rotation raising xx adds a node to the right spine of its left subtree (the path descending from its left child always to the right) or the left spine of its right subtree. Rotation count is therefore the sum of those spine lengths in the final treap.

Proof

Key xix_i with i<ki < k lies on the right spine of the left subtree of xkx_k exactly when, among keys xi,…,xkx_i, \dots, x_k, the lowest priority belongs to xkx_k and the second-lowest to xix_i. If xkx_k were not lowest, an intermediate key or xix_i would be above it and xix_i would not descend from xkx_k; if any among xi+1,…,xk−1x_{i+1}, \dots, x_{k-1} had priority lower than xix_i, it would lie between xkx_k and xix_i on the path and xix_i would lie to its left, off the spine. With j=k−i+1j = k - i + 1 keys, all priority orders are equally likely and the probability of those two particular positions is 1j(j−1)\frac{1}{j(j-1)}. Summing and telescoping,

∑i=1k−11(k−i+1)(k−i)=∑j=2k(1j−1−1j)=1−1k.\sum_{i=1}^{k-1} \frac{1}{(k - i + 1)(k - i)} = \sum_{j=2}^{k} \Big(\frac{1}{j - 1} - \frac{1}{j}\Big) = 1 - \frac1k.

The right side is symmetric, with n−k+1n - k + 1 instead of kk.

∎

This matters: a rotation writes memory, and writes are expensive in concurrent or persistent structures. A treap restructures O(1)\bigO(1) nodes on average per update, like a red–black tree (at most two rotations on insertion and three on deletion, though it may recolor an entire path).

Expected depth

The key question is how many ancestors a key has. The next lemma turns it into a priority question without inspecting the tree.

Proof

Let SS be the keys between xix_i and xkx_k inclusive, and xsx_s the lowest-priority key of SS. Follow the path from root to xkx_k. While no path node belongs to SS, every node’s key is below all of SS or above all, so xix_i and xkx_k enter the same subtree and stay together. The first node of SS on the path is xsx_s: in the subtree containing all of SS the root has lowest priority, and by heap order no node of SS can be above xsx_s. If xs≠xi,xkx_s \ne x_i, x_k, key xix_i goes to one side of xsx_s and xkx_k to the other, so xix_i is not an ancestor of xkx_k. If xs=xix_s = x_i, then xix_i lies on the path to xkx_k: it is an ancestor. If xs=xkx_s = x_k, xkx_k is an ancestor of xix_i, not vice versa.

∎

This is exactly randomized quicksort’s criterion: xix_i and xkx_k are compared if and only if the first pivot chosen between them is one of the endpoints. A treap is literally quicksort’s recursion tree with pivots chosen by priority. With iid priorities, each key of SS is equally likely to be smallest, so P[xi es antepasado de xk]=1∣k−i∣+1\Pr[x_i \text{ es antepasado de } x_k] = \frac{1}{\abs{k - i} + 1}. Summing with indicator variables:

You will prove the first equality in the final guided exercise. The bound follows from Hm≤1+ln⁡mH_m \le 1 + \ln m: Hk+Hn−k+1−2≤ln⁡k+ln⁡(n−k+1)≤2ln⁡n+12<2ln⁡nH_k + H_{n-k+1} - 2 \le \ln k + \ln(n - k + 1) \le 2\ln\frac{n+1}{2} < 2\ln n (the second inequality is logarithm concavity). Average over kk using ∑k=1nHk=(n+1)Hn−n\sum_{k=1}^n H_k = (n+1)H_n - n. In bits, 2ln⁡n≈1.39log⁡2n2\ln n \approx 1.39\log_2 n: a treap is 39% deeper on average than a perfect tree, as measured below. A red–black tree has worst-case height 2log⁡2(n+1)2\log_2(n + 1), though average depth is usually close to log⁡2n\log_2 n.

With high probability

Expectation is insufficient for an index: you want no slow searches. This requires concentration, and a non-obvious property appears. Split the depth of xkx_k into left and right ancestors, Dk=Lk+RkD_k = L_k + R_k, with Lk=∑i<kAikL_k = \sum_{i < k} A_{ik}. Read priorities of xk−1,xk−2,…,x1x_{k-1}, x_{k-2}, \dots, x_1 in that order, starting with xkx_k: by the lemma, Aik=1A_{ik} = 1 exactly when the priority of xix_i is a new minimum of the sequence, a record. Record indicators of a continuous iid sequence are independent: whether position jj is a record depends only on where the minimum falls among the first jj, not the earlier relative order (a Rényi result proved by counting permutations). Thus LkL_k is a sum of independent Bernoullis with mean Hk−1≤ln⁡nH_k - 1 \le \ln n, and likewise RkR_k.

Proof

The upper-tail multiplicative Chernoff bound, P[X≥(1+δ)μ]≤(eδ/(1+δ)1+δ)μ\Pr[X \ge (1+\delta)\mu] \le \big(e^\delta/(1+\delta)^{1+\delta}\big)^{\mu}, remains valid if μ\mu is replaced by any upper bound μH≥μ\mu_H \ge \mu (the proof only uses E[etX]≤eμ(et−1)\E[e^{tX}] \le e^{\mu(e^t - 1)}, increasing with μ\mu). With X=LkX = L_k, μH=ln⁡n\mu_H = \ln n and 1+δ=2e1 + \delta = 2e, the exponent is δ−(1+δ)ln⁡(1+δ)=2e−1−2e(1+ln⁡2)=−1−2eln⁡2≈−4.768\delta - (1+\delta)\ln(1+\delta) = 2e - 1 - 2e(1 + \ln 2) = -1 - 2e\ln 2 \approx -4.768, so P[Lk≥2eln⁡n]≤n−4.76\Pr[L_k \ge 2e\ln n] \le n^{-4.76}. Likewise for RkR_k. If Dk≥4eln⁡nD_k \ge 4e\ln n, one of the two is at least 2eln⁡n2e\ln n, giving P[Dk≥4eln⁡n]≤2n−4.76\Pr[D_k \ge 4e\ln n] \le 2n^{-4.76}. By the union bound over nn keys, P[altura≥4eln⁡n]≤2n−3.76≤2n−3.7\Pr[\text{altura} \ge 4e\ln n] \le 2n^{-3.76} \le 2n^{-3.7}.

∎

Constant 4e≈10.94e \approx 10.9 is very pessimistic: Devroye showed in 1986 that random BST height is (4.311…+o(1))ln⁡n(4.311\ldots + o(1))\ln n with probability tending to 1. The result’s form matters: logarithmic average depth plus independence gives polynomially small tail bounds, enough to use a treap where a red–black tree would be used unless a deterministic guarantee is required.

Split and merge: two primitives for everything

The cleanest way to program a treap uses two recursive operations instead of explicit rotations:

  • split⁡(T,a)\operatorname{split}(T, a) splits TT into two treaps: T<T_< with keys below aa and T≥T_\ge with the rest.
  • merge⁡(L,R)\operatorname{merge}(L, R) joins two treaps with every key in LL smaller than every key in RR.

merge chooses the root by comparing the two roots’ priorities: if LL wins, retain its left subtree and make its right subtree merge⁡(L.der,R)\operatorname{merge}(L.\text{der}, R); if RR wins, reverse the roles. split descends the search path for aa and at each node decides its side and which part of its child it keeps. Both traverse a tree path (merge, the right spine of LL and left spine of RR), costing expected O(profundidad)=O(log⁡n)\bigO(\text{profundidad}) = \bigO(\log n). Both preserve both orders: check this before reading the implementation and program it in the coding exercise.

Everything else takes two lines with them:

  • Insert xx: (L,R)=split⁡(T,x)(L, R) = \operatorname{split}(T, x) and return merge⁡(merge⁡(L,{x}),R)\operatorname{merge}(\operatorname{merge}(L, \{x\}), R).
  • Delete xx: find its node and replace it with merge⁡\operatorname{merge} of its two children.
  • Union of sets AA and BB: the lower-priority root, say from AA, splits BB by its key, then recurse on each side. Blelloch and Reid-Miller (1998) showed union, intersection and difference of treaps of sizes m≤nm \le n cost expected O(mlog⁡(n/m+1))\bigO(m\log(n/m + 1)), optimal, with independent recursions that parallelize naturally.

With split and merge by position, a sequence supports expected O(log⁡n)\bigO(\log n) insertion or deletion anywhere, cutting and pasting ranges, concatenation, and with a lazy flag, reversing a whole range: split it out, mark its root “reversed” and merge again. The flag propagates to children (swapping them) only when an operation descends through the node. This is natural for a text editor (rope) or sequence problems with range operations; you will build it below.

Skip lists: lists with express lanes

Searching a sorted linked list costs O(n)\bigO(n). Pugh’s idea (1990) is to add express lanes: a second list with about half the nodes, a third with a quarter, and so on. Search descends a staircase: advance along the highest lane without overshooting, then drop a lane when the next node is too large.

To search yy, start at the header at level HH. At each level advance while the next key is less than yy; otherwise descend a level. At level 1 the next node is yy or it is absent. Insertion searches while remembering the last node visited at each level (predecessors), draws the new key’s level and links it on those levels; deletion unlinks it. No rotations or rebalancing: random levels do the work.

InteractiveSearching a skip list
level 4−∞561627303339425059627383889293+∞
  • search path (staircase)
  • current position (outline)
  • key found
step 10 / 10
Level 1: the next key is 62 > 61. The key is absent; 5 right moves and 3 descents.
Search steps, n = 4096
Pointers per key
0.50
61
Height HH4
Pointers (expected)29 (32.0)
Right moves + descents5 + 3 = 8
Step bound, nn = 409626.0
Measured·
Above is a skip list with towers (one per key, height equal to level) and pointers; header and end are −∞-\infty and +∞+\infty. Choose a key and animate the search: the magenta path is a staircase of rightward moves and descents. Change pp: each node keeps its random number, so towers grow or shrink without changing order. Below is the trade-off for 4,096-key lists: expected search steps (bound and measured mean) and pointers per key, 1/(1−p)1/(1-p). Notice how flat the steps curve is between p=1/4p = 1/4 and p=1/2p = 1/2, despite different pointer costs.

Analyze the three quantities that matter using familiar tools.

Proof

(1) Each key contributes ℓ(x)\ell(x) pointers and E[ℓ(x)]=∑j≥1P[ℓ(x)≥j]=∑j≥1pj−1=11−p\E[\ell(x)] = \sum_{j \ge 1}\Pr[\ell(x) \ge j] = \sum_{j \ge 1} p^{j-1} = \frac{1}{1-p}; sum by linearity.

(2) H>hH > h if and only if some key has level at least h+1h + 1, each with probability php^h: by the union bound, P[H>h]≤nph\Pr[H > h] \le n p^h. If h≥(1+c)log⁡1/pnh \ge (1+c)\log_{1/p} n, then ph≤n−(1+c)p^h \le n^{-(1+c)} and the bound is n−cn^{-c}. For expectation, E[H]=∑h≥0P[H>h]≤L+∑h≥Lnph≤L+npL1−p≤L+11−p\E[H] = \sum_{h \ge 0}\Pr[H > h] \le L + \sum_{h \ge L} n p^h \le L + \frac{np^L}{1-p} \le L + \frac{1}{1-p} because npL≤1np^L \le 1.

(3) Backward analysis. Traverse the search path backwards from the last node visited at level 1. When at a node at level jj, its level is at least jj; the forward path arrived by descending from level j+1j + 1 if the node’s level exceeds jj, or by advancing from the left otherwise. Conditioned on everything seen, the node’s level exceeds jj with probability pp: each backward step rises with probability pp (or 1 at the header) and otherwise moves left. Expected steps to accumulate L−1L - 1 ascents are at most (L−1)/p(L - 1)/p, a negative binomial expectation. Above level LL remain at most (H−L)+(H - L)^+ ascents, with expectation ≤11−p\le \frac{1}{1-p} by (2), and leftward moves through nodes of level at least LL, of which npL−1≤1/pnp^{L-1} \le 1/p exist on average. Sum to obtain L−1p+1p+11−p\frac{L-1}{p} + \frac1p + \frac{1}{1-p}.

∎

The dominant cost term is log⁡1/pnp=ln⁡npln⁡(1/p)\frac{\log_{1/p} n}{p} = \frac{\ln n}{p\ln(1/p)}. Function pln⁡(1/p)p\ln(1/p) peaks at p=1/ep = 1/e, minimizing steps there: eln⁡n≈1.88log⁡2ne\ln n \approx 1.88\log_2 n. But the maximum is flat: p=1/2p = 1/2 and p=1/4p = 1/4 give exactly 2log⁡2n2\log_2 n because 12ln⁡2=14ln⁡4\frac{1}{2}\ln 2 = \frac{1}{4}\ln 4. For pointers, p=1/4p = 1/4 uses 4/34/3 per key versus 22. Thus Pugh recommended p=1/4p = 1/4, as measured in the implementation section. Search cost is also concentrated: steps to accumulate LL ascents exceed tt only if a binomial Bin⁡(t,p)\Bin(t, p) falls below LL, and Chernoff’s lower tail makes this probability polynomially small for t=cL/pt = c L/p with constant cc.

Why concurrent systems favor them. Skip-list insertion changes only the new key’s predecessor pointers, 1/(1−p)1/(1-p) on average; no rotations reorganize entire subtrees and no recoloring climbs to the root. Level 1 is authoritative and higher levels are shortcuts: a search encountering a half-built shortcut remains correct because it can descend to level 1. This permits lock-free versions linking each level with atomic compare-and-swap (Fraser, 2004; Herlihy and Shavit develop this in The Art of Multiprocessor Programming). In practice Java ConcurrentSkipListMap is a lock-free skip list; LevelDB and RocksDB’s memtable, accumulating recent writes before disk flush, is a skip list; Redis sorted sets (ZADD, ZRANGE) combine a skip list and hash table beyond a few elements.

Splay trees: trees that reorganize on reads

A splay tree (Sleator and Tarjan, 1985) is a BST with no balance field, where every operation ends by raising the last node touched to the root using splay⁡(x)\operatorname{splay}(x). While xx is not the root, let yy be its parent and zz its grandparent:

  • zig: if yy is root, rotate xx with yy. This occurs only at the last step.
  • zig-zig: if xx and yy are both left children (or both right), first rotate yy with zz, then xx with yy.
  • zig-zag: if xx is a left child and yy right, or vice versa, rotate xx with yy, then xx with zz.

Search xx by descending to xx (or the last path node if absent) and splaying it. Insert by attaching and splaying the leaf. Delete by splaying xx, removing the root and joining the subtrees: splay the left maximum, now root without a right child, and attach the right subtree.

Zig-zag is the obvious move: two rotations of xx. Zig-zig changes everything. The obvious alternative, rotate to root (raise xx through single parent rotations, proposed by Allen and Munro in 1978), also brings xx to the root but leaves most of the path intact. Zig-zig folds the path onto itself and roughly halves the depth of all nodes on the access path. The figure compares both methods.

InteractiveSplay versus rotate-to-root
Splay (zig-zig and zig-zag)
123456789101112131415
Splay: rotation pairs depend on the shape of the path.
Move to root (single rotations)
123456789101112131415
Move to root: one single rotation after another.
  • selected key, splay
  • selected key, single rotations
  • nodes rotating in this step
1
Accesses0
Last access (nodes): splay / single· / ·
Cumulative cost, splay0
Cumulative cost, single rotations0
Height: splay / single14 / 14
Potential Φ=∑log⁡2s(x)\Phi = \sum \log_2 s(x)40.3 / 40.3
Both trees start as the same 15-key path (each the next one's left child) and receive the same accesses; each animation step is a rotation. Access 1: both make 14 rotations, but splay leaves height 8 and single rotations leave height 14. Observe potential Φ=∑xlog⁡2s(x)\Phi = \sum_x \log_2 s(x): splay falls from 40.3 to 23.2 and the other does not move. Now traverse 1, 2, …, 15 repeatedly: after each pass both return to the initial path, from which a pass costs 134 nodes with single rotations and 63 with splay; the difference grows like n2n^2 versus nn. Also try starting from a random BST.

Single rotations admit sequences costing Θ(n)\Theta(n) per access indefinitely: in the figure’s path, traversing keys in order costs n+n(n+1)2−1n + \frac{n(n+1)}{2} - 1 nodes per pass, leaving the tree unchanged each time. A particular splay operation can also cost Θ(n)\Theta(n) (the first access to 1 traverses all 15 nodes), but this cannot repeat indefinitely: amortized analysis makes that a theorem.

The access lemma

The analysis uses the potential method with a potential measuring tree imbalance. Assign each key an arbitrary weight w(x)>0w(x) > 0 (the algorithm neither knows nor uses it: it is an analysis tool) and define

s(x)=∑y∈subaˊrbol(x)w(y),r(x)=log⁡2s(x),Φ(T)=∑x∈Tr(x).s(x) = \sum_{y \in \text{subárbol}(x)} w(y), \qquad r(x) = \log_2 s(x), \qquad \Phi(T) = \sum_{x \in T} r(x).

s(x)s(x) is weighted subtree size and r(x)r(x) its rank. A path has high potential (many large subtrees) and a balanced tree low potential: with unit weights, Φ\Phi of the 15-key path is log⁡215!≈40.25\log_2 15! \approx 40.25 versus about 15.915.9 for a perfect tree. Actual splay cost is the number of rotations (or 1 if xx is already root), and amortized cost adds the potential increase.

The proof analyzes each step separately and sums. Below, rr and r′r' are ranks before and after a step. Only rotating-node ranks change, and the rank of xx afterward is the previous top rank: after zig-zig or zig-zag, r′(x)=r(z)r'(x) = r(z). The only tool is a concavity inequality.

Proof

By the arithmetic–geometric mean inequality, ab≤(a+b2)2≤c24ab \le \left(\frac{a+b}{2}\right)^2 \le \frac{c^2}{4}. Set log⁡2\log_2.

∎
Proof

Access lemma, step by step. It suffices to prove amortized zig cost at most 3(r′(x)−r(x))+13(r'(x) - r(x)) + 1 and zig-zig or zig-zag cost at most 3(r′(x)−r(x))3(r'(x) - r(x)). Summing all steps telescopes terms to 3(rfinal(x)−r(x))+13(r_{\text{final}}(x) - r(x)) + 1, +1+1 appears once because only the final step can be zig, and ultimately xx is root with rfinal(x)=r(t)r_{\text{final}}(x) = r(t) because total weight is unchanged.

Zig (one rotation, cost 1). Only r(x)r(x) and r(y)r(y) change, with r′(x)=r(y)r'(x) = r(y), so ΔΦ=r′(y)−r(x)\Delta\Phi = r'(y) - r(x). Since yy ends below xx, r′(y)≤r′(x)r'(y) \le r'(x), and amortized cost is 1+ΔΦ≤1+(r′(x)−r(x))≤1+3(r′(x)−r(x))1 + \Delta\Phi \le 1 + (r'(x) - r(x)) \le 1 + 3(r'(x) - r(x)) because r′(x)≥r(x)r'(x) \ge r(x).

Zig-zag (two rotations, cost 2). With r′(x)=r(z)r'(x) = r(z), ΔΦ=r′(y)+r′(z)−r(x)−r(y)\Delta\Phi = r'(y) + r'(z) - r(x) - r(y). Since yy was above xx, r(y)≥r(x)r(y) \ge r(x) and ΔΦ≤r′(y)+r′(z)−2r(x)\Delta\Phi \le r'(y) + r'(z) - 2r(x). Afterward yy and zz are the two children of xx with disjoint subtrees, so s′(y)+s′(z)≤s′(x)s'(y) + s'(z) \le s'(x) and by concavity r′(y)+r′(z)≤2r′(x)−2r'(y) + r'(z) \le 2r'(x) - 2. Amortized cost is 2+ΔΦ≤2(r′(x)−r(x))≤3(r′(x)−r(x))2 + \Delta\Phi \le 2(r'(x) - r(x)) \le 3(r'(x) - r(x)).

Zig-zig (two rotations, cost 2). This distinguishes splay from rotate-to-root; you will prove it in the final guided exercise using the same concavity lemma on another pair of disjoint subtrees.

∎

The theorem’s 3 comes from zig-zig; zig-zag needs only 2. The argument also shows why single rotations fail: in a “rotate xx twice” step on a straight path, the lemma’s disjoint subtrees do not exist, and potential may not decrease despite paying for two rotations. The figure showed this: fourteen rotations with ΔΦ=0\Delta\Phi = 0.

Proof

With unit weights, s(t)=ns(t) = n and s(x)≥1s(x) \ge 1, so each splay costs at most 3log⁡2n+13\log_2 n + 1 amortized. Total actual cost is total amortized cost minus Φfinal−Φinicial\Phi_{\text{final}} - \Phi_{\text{inicial}} and, since 0≤Φ≤nlog⁡2n0 \le \Phi \le n\log_2 n, the difference is bounded by nlog⁡2nn\log_2 n.

∎

Insertion and deletion are also amortized O(log⁡n)\bigO(\log n). Attaching a new leaf increases its ancestors’ sizes s1<s2<⋯<sds_1 < s_2 < \cdots < s_d (bottom-up) by one; since si+1≥si+1s_{i+1} \ge s_i + 1, potential rises by at most ∑i=1dlog⁡2si+1si≤∑i=1d−1log⁡2si+1si+log⁡2sd+1sd=log⁡2sd+1s1≤log⁡2(n+1)\sum_{i=1}^{d} \log_2\frac{s_i + 1}{s_i} \le \sum_{i=1}^{d-1} \log_2\frac{s_{i+1}}{s_i} + \log_2\frac{s_d + 1}{s_d} = \log_2\frac{s_d + 1}{s_1} \le \log_2(n+1) (a telescoping sum, with s1≥1s_1 \ge 1 and sd=ns_d = n). The subsequent splay pays the rest.

What splay learns without being told

The access lemma holds for any weight assignment, and the algorithm does not depend on weights. Thus the same splay tree simultaneously satisfies all bounds obtained by choosing different analysis weights. For an access sequence x1,…,xmx_1, \dots, x_m, total cost is at most

∑j=1m(3log⁡2Ww(xj)+1)+∑xlog⁡2Ww(x),W=∑xw(x),\sum_{j=1}^m \Big(3\log_2\frac{W}{w(x_j)} + 1\Big) + \sum_{x}\log_2\frac{W}{w(x)}, \qquad W = \sum_x w(x),

where the second term bounds potential decrease (s(x)≤Ws(x) \le W initially and s(x)≥w(x)s(x) \ge w(x) finally). Each choice of weights gives a theorem:

  • Static optimality. If key xx is accessed q(x)≥1q(x) \ge 1 times, with w(x)=q(x)/mw(x) = q(x)/m cost is O(m+∑xq(x)log⁡mq(x))=O(m(1+H))\bigO\big(m + \sum_x q(x)\log\frac{m}{q(x)}\big) = \bigO(m(1 + \mathcal{H})), where H\mathcal{H} is frequency entropy. Any static BST costs at least mH/log⁡23m\mathcal{H}/\log_2 3 because each search is a sequence of three-outcome comparisons (less, equal, greater) and the ternary-code entropy bound applies. Thus splay is as good up to constants as the optimal static BST built knowing frequencies in advance, without knowing them.
  • Static finger. With w(x)=1/(1+∣x−f∣)2w(x) = 1/(1 + \abs{x - f})^2 for fixed key ff, W≤1+2∑d≥1d−2<4.3W \le 1 + 2\sum_{d \ge 1} d^{-2} < 4.3 and cost is O(m+nlog⁡n+∑jlog⁡(∣xj−f∣+1))\bigO\big(m + n\log n + \sum_j \log(\abs{x_j - f} + 1)\big): accessing near a finger is cheap, regardless of which finger.
  • Working set. Let tjt_j count distinct keys accessed since the last access to xjx_j. Cost is O(m+nlog⁡n+∑jlog⁡(tj+1))\bigO\big(m + n\log n + \sum_j \log(t_j + 1)\big). The proof uses time-varying weights, w(x)=1/k2w(x) = 1/k^2 if xx is the kk-th most recent key; after accessing xjx_j its weight becomes 1 and the tjt_j more recent keys move down one rank, and this adjustment does not increase potential. This is the stack distance of an LRU cache: a splay tree behaves like a cache without having one.
  • Sequential access. Accessing all keys in order costs O(n)\bigO(n) total (Tarjan, 1985), constant amortized, even if each access starts far from the root.
  • Dynamic finger. Stronger than static finger: cost is O(m+n+∑jlog⁡(∣xj−xj−1∣+1))\bigO\big(m + n + \sum_j \log(\abs{x_j - x_{j-1}} + 1)\big). Cole and coauthors proved it in 2000 in two papers and dozens of pages, not as a consequence of the access lemma.
InteractiveA splay tree learns your accesses
Nodes visited per access, 100-access moving average (4000 accesses, n = 255)
  • splay
  • red-black
  • optimal static (offline)
Red-black height: 10. Optimal static height: 17. Splay starts from a perfectly balanced tree.
Cost per access after each working-set change (mean of 13 changes, in groups of 3 accesses)
  • splay
  • red-black
  • optimal static (offline)
Access pattern
8
Number of keys nn
Splay (nodes per access)3.34
Red-black7.33
Optimal static (offline)5.36
Frequency entropy HH6.39 bits
Mean of log⁡2(t+1)\log_2(t+1)2.06
log⁡2n\log_2 n7.99
Splay wins: 3.34 nodes per access versus 5.36 for the best static tree, which knows the entire sequence in advance.
The same sequence of 4,000 accesses to keys 1 through nn for three trees: splay (initially perfectly balanced), a fixed red–black tree and the optimal static BST for whole-sequence frequencies, computed in advance by Knuth's algorithm. The upper graph shows moving average nodes traversed per access. With locality (a working set of 8 active keys changing every 300 accesses), splay costs about 3.3 nodes and beats even static optimum (5.4) by tracking changes: the lower graph averages accesses after each set change, where splay starts near 9 nodes and returns to low cost in about twenty accesses while fixed-tree cost stays unchanged. With Zipf, static optimum wins, but splay is within about 1.5 times without knowing frequencies and beats red–black. Sequential access costs constant time. Uniform access has nothing to learn, so splay loses to red–black: the price of restructuring on every read.

The figure shows both sides. With structure (unequal frequencies, temporal locality, ordered traversals), splay exploits it without parameters or statistics. Without it, there is a constant cost: uniform accesses traverse about 30% more nodes than the fixed red–black tree shown (and 10% more than the deeper fixed treap in the splay cell), and each access writes as many rotations as nodes traversed minus one. In practice splay trees are mainly used with strong locality and one thread: FreeBSD organizes each process’s virtual-memory map entries in a splay tree, and GNU’s libiberty library used by GCC includes one.

The dynamic optimality conjecture

The bounds above compare splay with particular strategies. The ambitious question is whether it compares with all of them. Fix the BST model: to serve access to xjx_j, an algorithm touches a connected subtree containing the root and xjx_j, pays one unit per node touched and may reorganize those nodes into any BST. Let OPT(X)\mathrm{OPT}(X) be the minimum cost of any algorithm in that model knowing the whole sequence XX in advance.

Open since 1985, it is probably the best-known open problem in data structures. Splay is immediately O(log⁡n)\bigO(\log n)-competitive when starting from a balanced tree with potential O(n)\bigO(n): it costs (3log⁡2n+1)m+O(n)(3\log_2 n + 1)m + \bigO(n) and OPT(X)≥m\mathrm{OPT}(X) \ge m. Progress has followed three routes:

  • Lower bounds for OPT. Wilber (1989) gave two computable lower bounds on OPT(X)\mathrm{OPT}(X). The difficulty is there: proving near-optimality requires knowing the optimum’s cost, and there is no formula.
  • Nearly optimal trees. Tango trees (Demaine, Harmon, Iacono and Pătraşcu, 2004) are O(log⁡log⁡n)\bigO(\log\log n)-competitive, the first result below log⁡n\log n. They use Wilber’s first bound and maintain a reference tree’s “preferred paths” as auxiliary trees.
  • Problem geometry. Demaine, Harmon, Iacono, Kane and Pătraşcu (2009) showed that executing a BST algorithm corresponds to planar points (node touched, time) with a simple “arborally satisfied” combinatorial property, and OPT(X)\mathrm{OPT}(X) is, up to a constant factor, the smallest satisfied superset of access points. This language yields a greedy algorithm, Greedy (Lucas, 1988; Munro, 2000), also conjectured optimal and satisfying many splay properties.

Iacono (2013) surveys the state of the problem. It illustrates an open question with publishable partial results: special cases of the conjecture (for example, sequences avoiding certain patterns) continue to appear at leading conferences.

Persistence: versions that do not overwrite each other

All preceding structures are ephemeral: an update destroys the previous state. Sometimes it must be retained for undo, historical queries, consistent transaction snapshots or lock-free sharing between threads, since immutable data needs no protection from changes.

The naive method, copying the entire structure on each update, costs Θ(n)\Theta(n) per operation. The basic tree technique, path copying, observes that an update changes only nodes on the path from root to modification. Copy those nodes, point the copies at unchanged subtrees (shared with the old version), and use the copied root for the new version. In a tree of height O(log⁡n)\bigO(\log n), each update creates O(log⁡n)\bigO(\log n) nodes, and old versions remain intact because no existing node is modified.

InteractivePersistence by path copying
12v06v030v062v070v025v137v144v140v150v275v288v280v2
  • node copied or created in this version
  • shared node (label shows the version in which it was created)
Version 2 = version 1 + insertion of 80. Only 4 new nodes were created (the path from root to the new leaf); the other 9 are shared with earlier versions.
33
Nodes in the displayed version13
Nodes created by this version4
Nodes in memory (all versions)20
If each version were a complete copy36
Savings1.80×
Each button above is a version; each node's small label identifies the version where it was created. Orange marks nodes created by the displayed version: exactly the path from root to inserted key. Everything else is shared. Choose an old version and insert into it: the new version branches from there (full persistence), others unchanged. Readouts compare nodes in memory with copying each full version.

Path copying combines well with treaps (split and merge recurse along one path, so create nodes instead of modifying them) and red–black trees (rebalancing touches O(1)\bigO(1) nodes near the path). To reduce space below O(log⁡n)\bigO(\log n) per update, Driscoll, Sarnak, Sleator and Tarjan (1989) proposed two general techniques. With fat nodes, each field stores history as (version, value) pairs and a query in version vv finds the last value written in a version at most vv, at a factor O(log⁡m)\bigO(\log m) in access time. With node copying, each node has a few spare modification fields and is copied only when they fill; for bounded in-degree structures this gives partial persistence with O(1)\bigO(1) extra amortized space and time per modification. A classic application is Sarnak and Tarjan’s (1986) planar point location: a sweep with a persistent search tree gives O(log⁡n)\bigO(\log n) per query using O(n)\bigO(n) space.

Outside textbooks the idea is everywhere:

  • git. A commit points to a directory tree, each directory to entries and each file to content, all identified by content hash. Changing a file creates a new object for it, one per directory on the path to root, and a new commit: path copying in a Merkle graph, with everything else shared across versions (used in git for research).
  • Functional languages. Clojure and Scala vectors and maps and JavaScript immutable libraries use width-32 tries with path copying, so a “modification” creates about log⁡32n\log_{32} n nodes. Haskell Data.Map is a size-balanced tree using the same technique.
  • Databases and file systems. LMDB stores data in a copy-on-write B+tree: a transaction copies the path of pages it modifies and commit atomically changes the root, so readers always see a consistent snapshot without blocking anyone. Btrfs uses the same idea for snapshots.

Implementation from scratch

Start with a treap using split and merge. Both functions reuse nodes (they are destructive), usual for an ephemeral structure. Check both orders and measure average depth for random and increasing insertion orders, the latter an unbalanced BST’s worst case.

[ ]Treap with split and mergeBrowser
import random, math

class Nodo:
    __slots__ = ("clave", "pri", "izq", "der")
    def __init__(self, clave, pri):
        self.clave, self.pri = clave, pri
        self.izq = self.der = None

def split(t, a):
    """Parte t en (claves < a, claves >= a). Reutiliza los nodos: t deja de ser válido."""
    if t is None:
        return None, None
    if t.clave < a:
        t.der, r = split(t.der, a)
        return t, r
    l, t.izq = split(t.izq, a)
    return l, t

def merge(l, r):
    """Une dos treaps con todas las claves de l menores que todas las de r."""
    if l is None or r is None:
        return l or r
    if l.pri < r.pri:                  # montículo de mínimo: la menor prioridad es la raíz
        l.der = merge(l.der, r)
        return l
    r.izq = merge(l, r.izq)
    return r

def insertar(t, clave, rnd=random.random):
    l, r = split(t, clave)
    return merge(merge(l, Nodo(clave, rnd())), r)

def borrar(t, clave):
    if t is None:
        return None
    if clave == t.clave:
        return merge(t.izq, t.der)
    if clave < t.clave:
        t.izq = borrar(t.izq, clave)
    else:
        t.der = borrar(t.der, clave)
    return t

def recorrer(t, prof=0):
    """Genera (clave, prioridad, profundidad) en orden simétrico."""
    if t is not None:
        yield from recorrer(t.izq, prof + 1)
        yield t.clave, t.pri, prof
        yield from recorrer(t.der, prof + 1)

def es_treap(t, lo=-math.inf, hi=math.inf):
    """Orden de búsqueda (claves dentro de (lo, hi)) y orden de montículo."""
    if t is None:
        return True
    if not (lo < t.clave < hi):
        return False
    for h in (t.izq, t.der):
        if h is not None and h.pri < t.pri:
            return False
    return es_treap(t.izq, lo, t.clave) and es_treap(t.der, t.clave, hi)

def H(n):
    return sum(1 / i for i in range(1, n + 1))

random.seed(1)
n = 2000
for nombre, orden in [("orden aleatorio", random.sample(range(n), n)), ("orden creciente", list(range(n)))]:
    medias, alturas = [], []
    for rep in range(10):
        t = None
        for c in orden:
            t = insertar(t, c)
        prof = [p for _, _, p in recorrer(t)]
        medias.append(sum(prof) / n)
        alturas.append(max(prof))
    print(f"{nombre:16s} profundidad media {sum(medias) / 10:.2f}   altura media {sum(alturas) / 10:.1f}   treap válido: {es_treap(t)}")
print(f"teoría: 2(1 + 1/n)H_n - 4 = {2 * (1 + 1 / n) * H(n) - 4:.2f}    2 ln n = {2 * math.log(n):.2f}    log2 n = {math.log2(n):.2f}")

for c in range(0, n, 2):
    t = borrar(t, c)
claves = [c for c, _, _ in recorrer(t)]
print("tras borrar las pares:", len(claves), "claves; ordenadas:", claves == list(range(1, n, 2)), "  treap válido:", es_treap(t))

With n=2000n = 2000, measured average depths (12.23 and 12.28, averaged over ten treaps) agree with theory, 12.36, and are the same for increasing keys: an unbalanced BST in that order would be a path of average depth 999.5. Height, about 23.5, is 2.1log⁡2n2.1\log_2 n and far from pessimistic bound 4eln⁡n≈834e\ln n \approx 83; Devroye’s constant gives 4.311ln⁡n≈32.84.311\ln n \approx 32.8, reached only asymptotically.

Now the implicit treap: the key is position, each node stores subtree size and a lazy reversal flag. Check it against a Python list over thousands of random operations.

[ ]Implicit treap: a sequence with range reversalBrowser
import random

class NodoS:
    __slots__ = ("val", "pri", "tam", "inv", "izq", "der")
    def __init__(self, val):
        self.val, self.pri, self.tam, self.inv = val, random.random(), 1, False
        self.izq = self.der = None

def tam(t):
    return t.tam if t else 0

def empujar(t):
    """Aplica la inversión pendiente de t: intercambia sus hijos y les pasa la marca."""
    if t is not None and t.inv:
        t.izq, t.der = t.der, t.izq
        for h in (t.izq, t.der):
            if h is not None:
                h.inv = not h.inv
        t.inv = False

def actualizar(t):
    t.tam = 1 + tam(t.izq) + tam(t.der)

def split_pos(t, k):
    """(los k primeros elementos, el resto)."""
    if t is None:
        return None, None
    empujar(t)
    if tam(t.izq) < k:
        t.der, r = split_pos(t.der, k - tam(t.izq) - 1)
        actualizar(t)
        return t, r
    l, t.izq = split_pos(t.izq, k)
    actualizar(t)
    return l, t

def merge_s(l, r):
    if l is None or r is None:
        return l or r
    if l.pri < r.pri:
        empujar(l)
        l.der = merge_s(l.der, r)
        actualizar(l)
        return l
    empujar(r)
    r.izq = merge_s(l, r.izq)
    actualizar(r)
    return r

def insertar_en(t, i, val):
    l, r = split_pos(t, i)
    return merge_s(merge_s(l, NodoS(val)), r)

def borrar_en(t, i):
    l, r = split_pos(t, i)
    _, r = split_pos(r, 1)
    return merge_s(l, r)

def invertir(t, i, j):
    """Invierte el tramo [i, j) en O(log n) esperado: solo se marca la raíz del tramo."""
    l, r = split_pos(t, i)
    m, r = split_pos(r, j - i)
    if m is not None:
        m.inv = not m.inv
    return merge_s(merge_s(l, m), r)

def a_lista(t, out=None):
    out = [] if out is None else out
    if t is not None:
        empujar(t)
        a_lista(t.izq, out)
        out.append(t.val)
        a_lista(t.der, out)
    return out

t = None
for ch in "treaps y splay trees":
    t = insertar_en(t, tam(t), ch)
t = invertir(t, 0, 6)
t = invertir(t, 9, 14)
print("".join(a_lista(t)))

random.seed(3)
t, ref = None, []
for paso in range(3000):
    op = random.random()
    if op < 0.5 or not ref:
        i, v = random.randint(0, len(ref)), random.randint(0, 99)
        t = insertar_en(t, i, v); ref.insert(i, v)
    elif op < 0.7:
        i = random.randrange(len(ref))
        t = borrar_en(t, i); del ref[i]
    else:
        i = random.randrange(len(ref)); j = random.randint(i, len(ref))
        t = invertir(t, i, j); ref[i:j] = ref[i:j][::-1]
print("3000 operaciones aleatorias; coincide con la lista de Python:", a_lista(t) == ref, "  longitud final:", len(ref))

Notice where empujar is called: always before inspecting a node’s children. This is the same discipline as lazy propagation in the next lesson’s segment trees; forgetting it once causes bugs appearing only for particular operation sequences.

The splay tree uses parent pointers and counters for visited nodes and rotations. Compare it with a fixed treap (random-BST shape, not adaptive) across four access patterns, alongside frequency entropy and the working-set theorem’s average log⁡2(t+1)\log_2(t + 1).

[ ]Splay tree with rotation counterBrowser
import random, math
from collections import Counter

class Splay:
    """Splay tree con punteros al padre. Cuenta nodos recorridos y rotaciones."""
    class N:
        __slots__ = ("k", "l", "r", "p")
        def __init__(self, k):
            self.k, self.l, self.r, self.p = k, None, None, None

    def __init__(self):
        self.raiz, self.rotaciones, self.recorridos = None, 0, 0

    def _rotar(self, x):
        p, g = x.p, x.p.p
        if p.l is x:
            p.l, x.r = x.r, p
            if p.l: p.l.p = p
        else:
            p.r, x.l = x.l, p
            if p.r: p.r.p = p
        p.p, x.p = x, g
        if g is None: self.raiz = x
        elif g.l is p: g.l = x
        else: g.r = x
        self.rotaciones += 1

    def _splay(self, x):
        while x.p is not None:
            p, g = x.p, x.p.p
            if g is None:
                self._rotar(x)                          # zig
            elif (g.l is p) == (p.l is x):
                self._rotar(p); self._rotar(x)          # zig-zig: primero el padre
            else:
                self._rotar(x); self._rotar(x)          # zig-zag

    def buscar(self, k):
        u, ultimo = self.raiz, None
        while u is not None:
            self.recorridos += 1
            ultimo = u
            if k == u.k: break
            u = u.l if k < u.k else u.r
        if ultimo is not None:
            self._splay(ultimo)                         # también se ajusta si la clave no está
        return u is not None

    def insertar(self, k):
        if self.raiz is None:
            self.raiz = self.N(k); return
        u = self.raiz
        while True:
            if k == u.k: break
            v = u.l if k < u.k else u.r
            if v is None:
                v = self.N(k); v.p = u
                if k < u.k: u.l = v
                else: u.r = v
                u = v; break
            u = v
        self._splay(u)

def secuencia(tipo, n, m, rnd):
    perm = list(range(n)); rnd.shuffle(perm)
    if tipo == "uniforme":
        return [rnd.randrange(n) for _ in range(m)]
    if tipo == "secuencial":
        return [j % n for j in range(m)]
    if tipo == "zipf 1.2":
        pesos = [r ** -1.2 for r in range(1, n + 1)]
        return [perm[r] for r in rnd.choices(range(n), weights=pesos, k=m)]
    out = []                                            # conjunto de trabajo: 16 claves activas
    for j in range(m):                                  # que cambian cada 500 accesos
        if j % 500 == 0:
            activas = rnd.sample(range(n), 16)
        out.append(rnd.choice(activas))
    return out

def entropia(seq):
    m = len(seq)
    return -sum(c / m * math.log2(c / m) for c in Counter(seq).values())

def media_conjunto_trabajo(seq, n):
    """Media de log2(t + 1), con t = claves distintas desde el último acceso a la misma clave."""
    ultimo, tot = {}, 0.0
    for j, k in enumerate(seq):
        t = len(set(seq[ultimo[k] + 1:j])) if k in ultimo else n
        tot += math.log2(t + 1); ultimo[k] = j
    return tot / len(seq)

rnd = random.Random(7)
n, m = 1023, 10000
estatico = None                                         # un treap fijo como referencia (insertar y recorrer, de la primera celda)
for c in rnd.sample(range(n), n):
    estatico = insertar(estatico, c, rnd.random)
prof = {c: p for c, _, p in recorrer(estatico)}
print(f"n = {n}, m = {m}, log2 n = {math.log2(n):.2f}")
print(f"{'patrón':12s} {'splay':>7s} {'rot/acc':>8s} {'treap fijo':>11s} {'H':>6s} {'log2(t+1)':>10s}")
for tipo in ["uniforme", "zipf 1.2", "secuencial", "trabajo 16"]:
    seq = secuencia(tipo, n, m, rnd)
    s = Splay()
    for c in rnd.sample(range(n), n):
        s.insertar(c)
    s.rotaciones = s.recorridos = 0
    for k in seq:
        s.buscar(k)
    fijo = sum(prof[k] + 1 for k in seq) / m
    ws = f"{media_conjunto_trabajo(seq, n):10.2f}" if tipo == "trabajo 16" else f"{'·':>10s}"
    print(f"{tipo:12s} {s.recorridos / m:7.2f} {s.rotaciones / m:8.2f} {fijo:11.2f} {entropia(seq):6.2f} {ws}")

The table summarizes the previous section. With uniform accesses, splay visits about 12.4 nodes versus 11.3 for the fixed tree, losing while rotating about 11 times per access. With Zipf exponent 1.2, splay drops to 6.8 nodes, near entropy (6.1 bits), while the fixed tree stays at 11.9 because it does not know popular keys. Sequential access costs about 5.2 nodes per access, constant as the sequential-access theorem predicts. A 16-key working set costs 4.5 nodes, tracking average log⁡2(t+1)\log_2(t + 1) of 2.95 with a small constant, versus the fixed tree’s 11.2.

The skip list has instrumented search. Measure pointers per key and search steps for four values of pp (average of three lists each), then the height distribution across 10410^4 skip lists of 1,000 keys against the union bound. Heights do not require constructing lists: they are the maximum level.

[ ]Skip list and height with high probabilityBrowser
import random, math
import numpy as np
import matplotlib.pyplot as plt

class SkipList:
    """Skip list con cabecera de nivel MAX. Cada nodo guarda su clave y sus punteros 'sig', uno por nivel."""
    MAX = 40

    class N:
        __slots__ = ("k", "sig")
        def __init__(self, k, niveles):
            self.k, self.sig = k, [None] * niveles

    def __init__(self, p, rnd):
        self.p, self.rnd = p, rnd
        self.cab = self.N(-math.inf, self.MAX)
        self.altura = 1                      # niveles en uso
        self.punteros = 0
        self.pasos = 0                       # avances + bajadas de la última búsqueda

    def _nivel(self):
        l = 1
        while l < self.MAX and self.rnd.random() < self.p:
            l += 1
        return l

    def _predecesores(self, k):
        """Último nodo con clave < k en cada nivel, de arriba abajo, contando pasos."""
        pred = [None] * self.MAX
        u, pasos = self.cab, 0
        for L in range(self.altura - 1, -1, -1):
            while u.sig[L] is not None and u.sig[L].k < k:
                u = u.sig[L]; pasos += 1
            pred[L] = u
            if L > 0:
                pasos += 1                   # bajada
        self.pasos = pasos
        return pred

    def buscar(self, k):
        x = self._predecesores(k)[0].sig[0]
        return x is not None and x.k == k

    def insertar(self, k):
        pred = self._predecesores(k)
        if pred[0].sig[0] is not None and pred[0].sig[0].k == k:
            return
        l = self._nivel()
        for L in range(self.altura, l):      # niveles nuevos: el predecesor es la cabecera
            pred[L] = self.cab
        self.altura = max(self.altura, l)
        x = self.N(k, l)
        for L in range(l):
            x.sig[L], pred[L].sig[L] = pred[L].sig[L], x
        self.punteros += l

rnd = random.Random(11)
n = 2048
print(f"n = {n}, media de 3 skip lists por cada p")
print(f"{'p':>6s} {'punteros/clave':>15s} {'1/(1-p)':>8s} {'pasos medios':>13s} {'cota L/p + 1/(1-p)':>19s} {'altura':>7s}")
for p in [1/2, 1/math.e, 1/4, 1/8]:
    ptr = pasos = alt = 0
    for rep in range(3):
        s = SkipList(p, rnd)
        claves = rnd.sample(range(10 * n), n)
        for c in claves:
            s.insertar(c)
        for c in claves[:1000]:
            assert s.buscar(c)
            pasos += s.pasos / 3000
        ptr += s.punteros / (3 * n)
        alt += s.altura / 3
    L = math.ceil(math.log(n) / math.log(1 / p))
    print(f"{p:6.3f} {ptr:15.3f} {1 / (1 - p):8.3f} {pasos:13.2f} {L / p + 1 / (1 - p):19.2f} {alt:7.1f}")

# altura en 10^4 skip lists con n = 1000 y p = 1/2: la altura es el máximo de n niveles geométricos
gen = np.random.default_rng(0)
n, R = 1000, 10_000
alturas = np.concatenate([gen.geometric(0.5, size=(1000, n)).max(axis=1) for _ in range(R // 1000)])
hs = np.arange(8, 25)
medida = np.array([(alturas > h).mean() for h in hs])
exacta = 1 - (1 - 0.5 ** hs) ** n
union = np.minimum(1, n * 0.5 ** hs)
print(f"\naltura media {alturas.mean():.2f}  (log2 n = {math.log2(n):.2f}),  máxima observada {alturas.max()}")
for h, e, x, u in zip(hs, medida, exacta, union):
    if h in (10, 12, 14, 16, 20):
        print(f"P[H > {h:2d}]: medida {e:.4f}   exacta {x:.4f}   cota de la unión n·2^-h = {u:.4f}")
for c in (1, 2):
    h = math.ceil((1 + c) * math.log2(n))
    print(f"c = {c}: P[H > {h}] medida {(alturas > h).mean():.1e}  <=  1/n^c = {1 / n**c:.1e}")

plt.figure(figsize=(6, 3.2))
plt.semilogy(hs, np.maximum(medida, 1e-5), "o", label="medida (10⁴ skip lists)")
plt.semilogy(hs, exacta, "-", label="exacta 1 − (1 − 2⁻ʰ)ⁿ")
plt.semilogy(hs, union, "--", label="cota de la unión n·2⁻ʰ")
plt.xlabel("h"); plt.ylabel("P[H > h]"); plt.ylim(1e-5, 1.5); plt.legend(); plt.tight_layout(); plt.show()

Pointers per key match 1/(1−p)1/(1-p) within about 1% or better, and measured steps stay below the bound in all four cases. The minimum is at p=1/ep = 1/e, with p=1/4p = 1/4 very close; p=1/2p = 1/2 costs little more for 50% more pointers; with p=1/8p = 1/8 towers are so short horizontal moves begin to dominate. Average height with n=1000n = 1000 is 11.3, slightly above log⁡2n≈10\log_2 n \approx 10, and the tail matches theory: for h≥14h \ge 14 union bound n2−hn2^{-h} is almost exact because the events summed are nearly disjoint, and with h=⌈2log⁡2n⌉=20h = \lceil 2\log_2 n\rceil = 20 measured frequency (0.0009) stays below 1/n1/n.

Finally, persistence: a treap where split and insertion create new nodes rather than modifying existing ones (nodes are immutable). Count nodes created per version.

[ ]Persistent treap by path copyingBrowser
import random, math
from dataclasses import dataclass

@dataclass(frozen=True)
class P:
    clave: int
    pri: float
    izq: "P | None" = None
    der: "P | None" = None

creados = 0
def nodo(clave, pri, izq, der):
    global creados
    creados += 1
    return P(clave, pri, izq, der)

def p_split(t, a):
    """Como split, pero sin tocar t: copia solo los nodos del camino."""
    if t is None:
        return None, None
    if t.clave < a:
        l, r = p_split(t.der, a)
        return nodo(t.clave, t.pri, t.izq, l), r
    l, r = p_split(t.izq, a)
    return l, nodo(t.clave, t.pri, r, t.der)

def p_insertar(t, clave, pri):
    """Inserción persistente: baja hasta el nivel que le toca a la prioridad nueva y parte ahí."""
    if t is None:
        return nodo(clave, pri, None, None)
    if pri < t.pri:
        l, r = p_split(t, clave)
        return nodo(clave, pri, l, r)
    if clave < t.clave:
        return nodo(t.clave, t.pri, p_insertar(t.izq, clave, pri), t.der)
    return nodo(t.clave, t.pri, t.izq, p_insertar(t.der, clave, pri))

def claves(t):
    return [] if t is None else claves(t.izq) + [t.clave] + claves(t.der)

def distintos(raices):
    vistos, pila = set(), [r for r in raices if r is not None]
    while pila:
        u = pila.pop()
        if id(u) in vistos:
            continue
        vistos.add(id(u))
        pila.extend(h for h in (u.izq, u.der) if h is not None)
    return len(vistos)

random.seed(5)
n = 4000
versiones = [None]
for c in random.sample(range(n), n):
    versiones.append(p_insertar(versiones[-1], c, random.random()))
copia_entera = sum(range(n + 1))
print(f"{n} versiones: {creados} nodos creados, {distintos(versiones)} distintos alcanzables")
print(f"por inserción: {creados / n:.2f} nodos;  2 ln n = {2 * math.log(n):.2f}")
print(f"copiando la estructura entera en cada versión: {copia_entera:,} nodos ({copia_entera / creados:.0f} veces más)")
v10 = versiones[10]
print("la versión 10 sigue intacta:", len(claves(v10)) == 10 and claves(v10) == sorted(claves(v10)))

Each insertion creates about 14.5 nodes: ancestors of the new node plus nodes cut by p_split, totaling a depth plus a constant. All 4,000 versions fit in about 58,000 nodes, 138 times fewer than copying each entire version, and version 10 remains exactly as it was.

In libraries and systems

Python’s standard library has no balanced search tree. The usual option is sortedcontainers, not a tree but a list of sorted lists of around a thousand elements: with modern caches this beats a pointer tree written in pure Python.

from sortedcontainers import SortedList   # pip install sortedcontainers

s = SortedList([5, 1, 9, 3])
s.add(4)
s.bisect_left(4), s[2], list(s.irange(3, 6))   # rango en O(log n), acceso por posición
StructureWhere it appears
Red–blackC++ std::map and std::set (libstdc++), Java TreeMap, Linux kernel (rbtree.h)
Skip listJava ConcurrentSkipListMap, LevelDB and RocksDB memtables, Redis sorted sets
Treap and implicit treapropes and sequences in competitive programming; Blelloch and Reid-Miller’s parallel set union
Splay treeFreeBSD virtual-memory map, GNU libiberty
Persistentgit, Clojure and Scala (path-copying tries), Haskell Data.Map, LMDB, Btrfs

Selection is straightforward: for worst-case latency, red–black (or AVL); for concurrency, skip list; for sequence or set operations (cut, paste, union), treap; for highly local accesses without concurrency, splay; and for disk data or data too large for cache, the preceding lesson’s B-tree.

Common mistakes

Exercises

ProofExpected depth in a treap
Prove: In a treap of nn keys x1<⋯<xnx_1 < \cdots < x_n with continuous iid priorities, expected depth of xkx_k is Hk+Hn−k+1−2H_k + H_{n-k+1} - 2.
0
Write depth as prof⁡(xk)=∑i≠kAik\operatorname{prof}(x_k) = \sum_{i \ne k} A_{ik}, where AikA_{ik} is 1 if xix_i is an ancestor of xkx_k and 0 otherwise.

Step 1 of 4. What is E[Aik]\E[A_{ik}]?

ProofThe access lemma for zig-zig
Prove: In a zig-zig step of splay⁡(x)\operatorname{splay}(x), with parent yy and grandparent zz, amortized cost (2 rotations plus potential change) is at most 3(r′(x)−r(x))3(r'(x) - r(x)).
0
Before the step, xx is a child of yy and yy of zz, both on the same side (say left), with xx subtrees AA and BB. Afterward xx roots the block, yy is its right child and zz is yy's right child; subtrees CC (formerly yy's right child) and DD (formerly zz's right child) hang from zz. Only ranks of xx, yy and zz change.

Step 1 of 3. How does ΔΦ=r′(x)+r′(y)+r′(z)−r(x)−r(y)−r(z)\Delta\Phi = r'(x) + r'(y) + r'(z) - r(x) - r(y) - r(z) simplify?

NumericSkip-list pointers
A skip list has n=106n = 10^6 keys and promotion probability p=1/4p = 1/4. What is the expected number of forward pointers, counting one per key and level (excluding the header)?
NumericDepth of the minimum key
In a treap with n=1000n = 1000 keys, what is the expected depth (edges from the root) of the minimum key?
NumericThe balance theorem bound
A splay tree has n=220n = 2^{20} keys and receives m=106m = 10^6 accesses. According to the balance theorem, what is the maximum average number of rotations per access? (Use bound (3log⁡2n+1)m+nlog⁡2n(3\log_2 n + 1)m + n\log_2 n and divide by mm.)
NumericSkip-list height bound
A skip list with p=1/2p = 1/2 has n=220n = 2^{20} keys. What union bound applies to P[H>40]\Pr[H > 40]?
QuizChoosing the structure
Choose structures for three systems: (a) an in-memory ordered index read and written by many threads concurrently; (b) a single-threaded compiler symbol cache repeatedly querying the same few names; (c) a real-time scheduler where no operation may exceed a fixed deadline. Which assignment is most reasonable?
QuizWhat zig-zig does
A BST is a path: 4 is root, 3 its left child, 2 the left child of 3 and 1 the left child of 2. Access 1. What tree results after splay and after rotating 1 to root with single rotations?
QuizPersistence and amortization
Make a splay tree persistent by path copying: each access creates a new version with the reorganized tree. What happens to its amortized O(log⁡n)\bigO(\log n) bound?
CodeTreap split and merge
Implement split(t, a), splitting treap t into (L, R) with keys in L below a and keys in R greater or equal, and merge(l, r), joining two treaps assuming every key in l is below every key in r. Nodes have fields clave, pri, izq and der; heap order is minimum (root has lowest priority). You may reuse nodes without copying. Tests check in-order traversal, heap order and logarithmic average depth of a treap built with your split and merge by inserting 2,000 keys in increasing order.
class Nodo:
  __slots__ = ("clave", "pri", "izq", "der")
  def __init__(self, clave, pri):
      self.clave, self.pri = clave, pri
      self.izq = self.der = None

def split(t, a):
  """Devuelve (L, R): claves < a en L y claves >= a en R."""
  # tu código
  return t, None

def merge(l, r):
  """Une l y r; todas las claves de l son menores que las de r."""
  # tu código
  return l if l is not None else r
Shift+Enter to run

Summary

Key idea
Two ways to balance a search tree without color rules: let randomness determine shape (treaps and skip lists, height O(log⁡n)\bigO(\log n) with high probability for any data order) or let accesses determine it (splay trees, amortized O(log⁡n)\bigO(\log n) and bounds adapting to entropy and locality without knowing them).
  • A treap is a BST on keys and heap on random priorities. Its unique shape is that of a randomly inserted BST: xix_i is an ancestor of xkx_k if it has the interval’s lowest priority, expected depth is Hk+Hn−k+1−2<2ln⁡nH_k + H_{n-k+1} - 2 < 2\ln n, and rotations per update average fewer than two.
  • split and merge suffice for insertion, deletion, set union and, with sizes and lazy flags, sequences with range reversal (implicit treap).
  • A skip list uses geometric levels: n/(1−p)n/(1-p) pointers, average height log⁡1/pn+O(1)\log_{1/p} n + \bigO(1) and height O(log⁡n)\bigO(\log n) with high probability by the union bound, and about log⁡1/pn/p\log_{1/p} n/p search steps by backward analysis. Local updates make it a leading concurrent ordered structure.
  • A splay tree raises each accessed node to the root with zig, zig-zig (parent first) and zig-zag. With Φ=∑log⁡2s(x)\Phi = \sum\log_2 s(x), the access lemma gives amortized 3(r(t)−r(x))+13(r(t) - r(x)) + 1; choosing weights yields balance, static optimality, static finger and working-set bounds. Whether it is O(1)\bigO(1)-competitive against any dynamic BST is the dynamic optimality conjecture, open since 1985.
  • Path copying makes a tree persistent with O(log⁡n)\bigO(\log n) new nodes per update; this underlies git, immutable maps and copy-on-write databases. Amortized bounds do not survive persistence.