Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithms · Data Structures

Balance by Chance.

Watch the explainer

A plain binary search tree can degrade to a O(n) chain if keys arrive in sorted order. Balanced trees like AVL and red-black fix this with intricate rebalancing rules. A treap takes a wonderfully lazy shortcut: give every node a random priority and require the tree to be a heap on those priorities as well as a BST on the keys (hence tree + heap = “treap”). Because the shape is now determined by the random priorities — not by the order keys were inserted — the tree is balanced in expectation, with height O(log n), using only simple rotations. Insert keys and watch random priorities rotate the tree into balance.

O(log n) expected height · BST on keys + max-heap on random priorities · rotations only
BST property

Keys obey binary-search order: left subtree < node < right subtree.

heap property

Priorities obey a max-heap: every node’s priority ≥ its children’s.

random priority

Each node gets a random priority on insertion — this decides the shape.

rotation

A local restructuring that fixes the heap property while preserving BST order.

treap.js — keys ordered, priorities heaped
Ready
Each node shows its key (top) and random priority (bottom). The tree is a BST on keys and a max-heap on priorities. Inserting a key places it by BST order, then rotates it up while its priority beats its parent’s. Insert to build.
0
nodes
0
height
–
last rotations

How it works

The trick is that a treap’s shape is uniquely determined by its set of (key, priority) pairs, regardless of insertion order — the BST-on-keys and heap-on-priorities constraints together leave exactly one valid tree. So if the priorities are random, the tree you get is the same as if you had inserted the keys in a random order, which is known to produce an expected height of O(log n). Insertion is simple: place the new key as a normal BST leaf, then, while it has a higher priority than its parent, rotate it upward — each rotation preserves the BST order but lifts the high-priority node toward the root, restoring the heap property. Deletion is the mirror: rotate the node down until it’s a leaf, then snip it.

1

Give each node a random priority

On insertion, assign the new key a random priority. The tree must satisfy BST order on keys and max-heap order on priorities simultaneously.

2

Insert as a BST leaf

Descend by key comparisons and attach the new node as a leaf, exactly as in an ordinary BST. This keeps the BST property but may violate the heap property.

3

Rotate up to fix the heap

While the new node’s priority exceeds its parent’s, rotate it up. Each rotation is a local restructuring that preserves BST order while moving the higher priority toward the root.

✓

Balanced in expectation

Because random priorities make the shape equivalent to random-order insertion, the expected height is O(log n). No AVL/red-black-style rules are needed — just rotations driven by priorities.

Height
O(log n) expected
Insert / delete
O(log n)
Rebalance
rotations only
Also called
randomized BST

The code

# treap insertion: BST on key, max-heap on random priority import random def insert(t, key): if t is None: return Node(key, priority=random.random()) if key < t.key: t.left = insert(t.left, key) if t.left.priority > t.priority: # heap violated t = rotate_right(t) # lift the child up else: t.right = insert(t.right, key) if t.right.priority > t.priority: t = rotate_left(t) return t # rotations preserve BST order, fix the heap

Quick check

1. What two structures is a treap at the same time?

2. Why does a treap stay balanced without complex rebalancing rules?

3. How is the heap property restored after inserting a key?

FAQ

What is a treap?

A randomized balanced BST that is at once a binary search tree on its keys and a max-heap on a random priority per node. Since its shape comes from the random priorities, not insertion order, it has O(log n) expected height and supports insert/delete/search in O(log n) expected time with only simple rotations.

How does a treap compare to AVL and red-black trees?

AVL and red-black trees guarantee worst-case O(log n) height via strict rules (more complex code). A treap only guarantees O(log n) in expectation, but it’s far simpler and supports split/merge easily — a popular choice when simplicity and those operations matter more than a worst-case bound.

What are split and merge on a treap?

Split divides a treap into two by a key (smaller keys in one, rest in the other); merge combines two treaps (all keys in one < all in the other) into one. Both are O(log n), and they make implicit-key treaps behave like arrays with fast range insert/erase/reverse.

What happens if two nodes get the same priority?

Priority ties can blur the unique shape and slightly hurt balance, but with wide-range random priorities (32–64 bits) collisions are negligible; implementations either rely on that or break ties deterministically. In practice it’s a non-issue.

The picture: sorted left to right, heaped top to bottom

40p9410p8830p8320p5360p9150p6145p4270p2680p25key on top, priority below. Parent priority is always larger. Height 4.
The page’s keys with fixed priorities. Reading left to right gives 10, 20, 30, 40, 45, 50, 60, 70, 80 (binary search tree order); reading any parent-to-child step shows a smaller priority (heap order). The highest priority, 94 on key 40, is the root, even though 40 was inserted fifth.

Worked example, step by step

Keys are inserted in the order 50, 30, 70, 20, 40, 60, 80, 10, 45, with priorities fixed in advance as 50→61, 30→83, 70→26, 20→53, 40→94, 60→91, 80→25, 10→88, 45→42. Each insert descends as in a binary search tree, then rotates the new node up while its priority beats its parent’s. “Rotations” counts rotations done by that one insert.

StepPriorityRotationsRoot afterHeight after
insert 5061050 (priority 61)1
insert 3083130 (priority 83)2
insert 7026030 (priority 83)3
insert 2053030 (priority 83)3
insert 4094240 (priority 94)3
insert 6091240 (priority 94)3
insert 8025040 (priority 94)4
insert 1088240 (priority 94)4
insert 4542040 (priority 94)4
again in sorted order, same priorities—540 (priority 94)4

There were 7 rotations over 9 inserts. Insert 30 rotated once because 83 beats 61, so 30 became the root; inserting 40 (priority 94) rotated twice and took the root from 30. Later, 60 (priority 91) climbed to the right of 40 in two rotations. The last row is the real lesson (it used 5 rotations, a different path to the same tree): building the same tree from the keys in sorted order, with the same priorities, gives the identical shape. The final shape depends only on the set of (key, priority) pairs, never on arrival order, which is what lets random priorities stand in for a random insertion order. A plain binary search tree given sorted input would be a chain of height 9.

Complexity and trade-offs

CaseTimeSpaceWhy
Treap search, insert, deleteO(log n) expected, O(n) worstO(n) plus one priority per nodeExpected, not guaranteed: it depends on the priorities being random and independent of the keys.
Plain binary search tree, sorted inputO(n) per operationO(n)Sorted keys form a chain: 9 sorted keys have height 9. A treap on 100,000 sorted keys with random priorities measured height 38, with about 1 rotation per insert on average.
AVL or red-black treeO(log n) worst caseO(n) plus a balance field or colour bitGuaranteed bound, but the update rules have many cases. The treap trades the guarantee for a very short implementation.
Skip listO(log n) expectedO(n) expected, several pointers per nodeAlso randomised. Simple, but pointer-heavy and not a tree.
Treap split and mergeO(log n) expected eachO(n)Because shape follows priorities, cutting at a key and joining two treaps are as short as insert, and give range operations and sequences.

The cost of the randomness is variance: any single run can be unlucky. Across 9 keys inserted in sorted order with random priorities, one run reached height 6, where 4 would be perfect. At scale the constant is modest, 38 against a perfect 17 for 100,000 keys, and a treap does not rebalance eagerly, so updates are cheap. Choose it when short code and easy split and merge matter more than a hard worst-case bound.

Common mistakes

  • Using the key (or a counter) as the priority

    Priorities must be independent of the keys. With priority equal to key, inserting 1..9 in order makes each new key the largest priority, so it rotates all the way to the root and the tree is a chain of height 9: no better than a plain tree.

  • Giving every node the same priority

    With a strict “child greater than parent” test, no rotation ever fires. Inserting 1..9 with every priority 5 yields a chain of height 9. Draw priorities from a wide random range (or random floats) so ties are rare.

  • Rotating in the wrong direction

    A new left child with a higher priority needs a right rotation of its parent. Using the left rotation instead reads the parent’s missing right child: inserting 50 with priority 10 and then 30 with priority 90 raises AttributeError in the natural implementation, because the rotation tries to lift None. When it does not crash, it breaks key order.

  • Expecting perfect balance

    Expected height is logarithmic, not minimal. Keys 1..9 inserted with priorities 31, 76, 70, 17, 48, 78, 61, 81, 75 form a tree of height 6, while 9 nodes could fit in height 4. A test that asserts a tight height bound will fail on valid treaps.

  • Checking only one of the two orders

    A treap is two invariants at once. A test that confirms the in-order keys are sorted proves nothing about priorities. Check both: in-order keys ascending, and every parent priority at least every child’s.

Where this shows up

  • Ordered sets and maps with little code

    When you need insertion, deletion and rank queries but not a worst-case guarantee, a treap is a few dozen lines. It is a common choice in programming contests for that reason.

  • Sequences with cut and paste

    Treated as an implicit-key tree (positions instead of keys), split and merge give cut, copy and reverse of a range in expected logarithmic time. Text and list structures are built this way.

  • Order statistics

    Storing subtree sizes in each node lets you ask “what is the k-th smallest?” or “how many keys are below x?” without extra structures; rotations just need to update two sizes.

  • A model for randomised data structures

    The argument that random priorities mimic random insertion order is the same idea behind randomised quicksort and skip lists. Learning it here transfers directly.

SOLVE IT YOURSELF

Solve it: balance a BST with random priorities

A treap is two structures in one node: a BST on the key, a heap on a random priority. Keep both invariants and the shape is whatever a random insertion order would have produced — balanced, with no balance factors or colours to track. Python or TypeScript.

YOUR TASK

Implement Treap with insert(key), search(key), delete(key), inorder() and height(). Priorities come from the supplied seeded generator. Duplicate inserts are ignored.

HINTS — 7 IDEAS
  1. Insert like a plain BST first — walk down on key comparisons and hang the new node off a leaf.
  2. That leaf placement can violate the heap: the new node may outrank its parent. Fix it by rotating it up, once per level, on the way back out of the recursion.
  3. A right rotation at n makes n.left the new subtree root and n its right child. Keys stay ordered because you only ever move a subtree that was already on the correct side.
  4. Delete is the mirror image: rotate the doomed node down, always promoting the higher-priority child, until it has at most one child — then splice it out.
  5. Rotating toward the higher-priority child is what keeps the heap intact during deletion. Promoting the lower one would break it immediately.
  6. The priorities are random, so the tree's shape is the shape of a random BST: expected height about 3·log₂ n, no rebalancing rules required.
  7. Same seed means same tree every run — that is the only reason a randomized structure can be unit-tested at all.
CPython · WebAssembly

Keep going

▶  Watch it explained

Treap: Time and Space Complexity, From First Principles

Finished this one? 0 / 99 Algorithms done
NextSplay Tree: Touch It, Lift It Next on the “Keeping a tree balanced” ladder · rung 5 of 5

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms