COMPUTER ENGINEER

← BlogDATA STRUCTURES / ALGORITHMSPython example pack ↓

Trees and indexes · 23 / 53

Splay trees, skip lists and treaps

Understand → trace → implement → justify

2 min reading · allow extra time for practice

Splay trees move an accessed node to the root using zig, zig-zig or zig-zag rotations. Individual operations may be linear, while sequence costs are amortised O(log n). Adaptation to recent access does not automatically implement LRU eviction.

Skip lists add random-height express lanes over an ordered list. Traverse right until overshooting, then descend. Independent geometric heights give expected logarithmic operations and linear space, not worst-case guarantees.

Treaps combine BST key order with heap order on random priorities. Rotations, split and merge support ordered operations. Priorities must be independent of keys for expected balance. Implicit treaps derive positions from subtree sizes and need correct lazy-tag propagation for sequence edits.

A worked trace

Splaying a deepest chain node may take many rotations; the next access to it at the root is O(1). Distinguish individual from sequence cost.

Cost and assumptions

Splay amortised O(log n); skip lists/treaps expected O(log n). Each permits O(n) worst-case operations.

Executable example

Run with Python 3. Assertions check a small example; they do not constitute a general correctness proof. Some advanced examples are explicitly small models or reference oracles, not full production implementations.

Python 3
from random import Random
rng = Random(42)
def random_height():
    h = 1
    while rng.random() < 0.5: h += 1
    return h
heights = [random_height() for _ in range(8)]
assert all(h >= 1 for h in heights)

TEST YOUR UNDERSTANDING

Your turn

What if treap priorities equal their keys?

Reveal the reasoning

BST and heap orders align and may force a chain. The independence assumption is lost.

Take it further

  1. Write down the input contract and the invariant before changing the example.
  2. Add empty, boundary, duplicate and adversarial cases where they are relevant. Compare with a simple oracle.
  3. Derive the cost under the stated model; measure several input sizes and explain discrepancies.

Primary reading & lecture notes

Original explanations in this course; these references provide proofs and further reading. Source links may cover the broader module.

Pat Morin · Open Data Structures ↗MIT 6.046J · Design and Analysis ↗
Solve the exercise before moving on.