Algorithm Atlas · worked example
See the algorithm, step by step
Keep BST order by key and heap order by random priority; insertion rotates a new node up and deletion merges its children.
This call is starting. Local values appear as they are initialized.
Data & variables
Changed Source indexExample input
insert5 insert2 insert8 insert1 delete2 inorderFollow the code. Data appears here when it enters scope.
Call stack · 1 frame
maincall 1
Rust source
Line 100fn csv<T: std::fmt::Display>(a: impl IntoIterator<Item = T>) -> String {
a.into_iter()
.map(|x| x.to_string())
.collect::<Vec<_>>()
.join(",")
}
type TreapLink = Option<Box<TreapNode>>;
struct TreapNode {
key: i32,
priority: u64,
left: TreapLink,
right: TreapLink,
}
fn merge_treaps(a: TreapLink, b: TreapLink) -> TreapLink {
match (a, b) {
(None, b) => b,
(a, None) => a,
(Some(mut a), Some(mut b)) => {
if a.priority > b.priority {
a.right = merge_treaps(a.right.take(), Some(b));
Some(a)
} else {
b.left = merge_treaps(Some(a), b.left.take());
Some(b)
}
}
}
}
fn treap_insert(root: TreapLink, key: i32, priority: u64) -> TreapLink {
let Some(mut n) = root else {
return Some(Box::new(TreapNode {
key,
priority,
left: None,
right: None,
}));
};
if key == n.key {
return Some(n);
}
if key < n.key {
n.left = treap_insert(n.left.take(), key, priority);
if n.left.as_ref().unwrap().priority > n.priority {
let mut top = n.left.take().unwrap();
n.left = top.right.take();
top.right = Some(n);
return Some(top);
}
} else {
n.right = treap_insert(n.right.take(), key, priority);
if n.right.as_ref().unwrap().priority > n.priority {
let mut top = n.right.take().unwrap();
n.right = top.left.take();
top.left = Some(n);
return Some(top);
}
}
Some(n)
}
fn treap_delete(root: TreapLink, key: i32) -> TreapLink {
let Some(mut n) = root else {
return None;
};
if key == n.key {
return merge_treaps(n.left.take(), n.right.take());
}
if key < n.key {
n.left = treap_delete(n.left.take(), key);
} else {
n.right = treap_delete(n.right.take(), key);
}
Some(n)
}
fn treap_operations(ops: &[(bool, i32)]) -> Vec<i32> {
let mut root = None;
let mut random = 0xC0FFEE_u64;
for &(insert, key) in ops {
random ^= random << 13;
random ^= random >> 7;
random ^= random << 17;
root = if insert {
treap_insert(root, key, random)
} else {
treap_delete(root, key)
};
}
fn walk(root: &TreapLink, out: &mut Vec<i32>) {
if let Some(n) = root {
walk(&n.left, out);
out.push(n.key);
walk(&n.right, out);
}
}
let mut out = Vec::new();
walk(&root, &mut out);
out
}
fn main() {
let result = csv(treap_operations(&[
(true, 5),
(true, 2),
(true, 8),
(true, 1),
(false, 2),
]));
println!("{result}");
}
Try your own version
Compare the visible input `insert5 insert2 insert8 insert1 delete2 inorder` with `insert3 insert1 insert5 delete3 inorder`. Predict why their results are `1,5,8` and `1,5`. Then change one legal value and explain whether the same invariant, bst order by key and heap order by priority, still applies.
Open personal copy in Playground ↗Start with this exact source and input, change a value, then use Run or Debug locally. This replay stays attached to the original example.
Recordings use a native Rust target. Playground runs on wasm32-wasip1; target-sized types such as usize can have different limits.

Understand it
Insert 5,2,8,1, then delete 2. Rotations or merges preserve key order and priority order, so inorder returns 1,5,8. The demo uses reproducible pseudorandom priorities; expected logarithmic balance is a probabilistic assumption, not a worst-case guarantee.
The worked program is a complete executable for this pattern. Its core function uses typed input so the state transitions remain visible. The challenge input contract is: Apply the space-separated insertN and deleteN tokens, then return the keys ascending at inorder. Keys form a set: inserting a present key and deleting an absent key change nothing. The visible fixture is insert5 insert2 insert8 insert1 delete2 inorder and its example result is 1,5,8. The implementation and additional semantic fixtures were checked against an independent reference calculation. Those bounded tests establish these examples; they are not a proof for all inputs or a measurement on an iPhone.
Return a canonical String from solve: lowercase true/false for booleans; decimal integers without extra signs, leading zeros or whitespace; comma-separated sequence values and semicolon-separated groups. Whole-number medians have no decimal suffix; half medians use .5. Do not append a newline to the returned value. Preserve the explicitly named textual sentinels such as none or #. Input fixtures are bounded so the demonstrated arithmetic fits its named Rust types; satisfy the stated input preconditions before applying the algorithm.
String and character-grid fixtures use ASCII unless the lesson explicitly specifies Unicode scalar values.
A problem is a good match for Randomized Treap when it asks for ordered sets with expected logarithmic operations. Here the concrete task is: Apply the space-separated insertN and deleteN tokens, then return the keys ascending at inorder. Keys form a set: inserting a present key and deleting an absent key change nothing. The visible input insert5 insert2 insert8 insert1 delete2 inorder is an example, not a definition of the whole problem. Ask what operations the solution must support and what the input guarantees. Choose it when the required operation sequence, query volume, or substring structure exceeds a simple scan or prefix summary; compare the real time and memory limits first. The right choice follows from those guarantees, not from a familiar noun in the prompt.
The decisive invariant is: Keep BST order by key and heap order by random priority; insertion rotates a new node up and deletion merges its children. Try to say why it applies to the task without quoting the implementation. Which fact becomes known after one update, and which possible answers remain? An advanced structure or offline query order packages an invariant across operations. Name what each node, block, or reordered query state stores. If that claim cannot be maintained on a legal input, the pattern is wrong or one of its preconditions is missing. A counterexample is more useful than a vague warning: change one property of the sample, trace the first two steps, and identify the exact claim that fails.
Compare costs before committing. The advertised bound is O(log n) expected operation · O(n) space; identify the operation responsible for it and the extra memory it needs. Then compare a straightforward alternative: a direct scan, full sort, or repeated recomputation may be easier but can pay for the same work many times. Do not choose the more elaborate method just because it has a famous name. For the sample, predict 1,5,8 and explain which part of the state lets the method reach that result.
When the prompt is ambiguous, ask about input size, ordering, duplicates, and required output format. Test empty ranges, repeated updates, undo operations where supported, and the exact boundary between adjacent blocks. Keep representation and operations separate in Rust. Verify a tiny instance against a straightforward reference implementation before optimizing. The Rust sketch can show a useful primitive without proving that the whole task is solved; connect each primitive to the requested output. You should be able to name a fitting case, a near miss, and the assumption separating them before writing the first line.
The pattern
Keep BST order by key and heap order by random priority; insertion rotates a new node up and deletion merges its children.
When to use it: ordered sets with expected logarithmic operations
Complexity: O(log n) expected operation · O(n) space
Input: insert5 insert2 insert8 insert1 delete2 inorder
Read the code
fn csv<T: std::fmt::Display>(a: impl IntoIterator<Item = T>) -> String {
a.into_iter()
.map(|x| x.to_string())
.collect::<Vec<_>>()
.join(",")
}
type TreapLink = Option<Box<TreapNode>>;
struct TreapNode {
key: i32,
priority: u64,
left: TreapLink,
right: TreapLink,
}
fn merge_treaps(a: TreapLink, b: TreapLink) -> TreapLink {
match (a, b) {
(None, b) => b,
(a, None) => a,
(Some(mut a), Some(mut b)) => {
if a.priority > b.priority {
a.right = merge_treaps(a.right.take(), Some(b));
Some(a)
} else {
b.left = merge_treaps(Some(a), b.left.take());
Some(b)
}
}
}
}
fn treap_insert(root: TreapLink, key: i32, priority: u64) -> TreapLink {
let Some(mut n) = root else {
return Some(Box::new(TreapNode {
key,
priority,
left: None,
right: None,
}));
};
if key == n.key {
return Some(n);
}
if key < n.key {
n.left = treap_insert(n.left.take(), key, priority);
if n.left.as_ref().unwrap().priority > n.priority {
let mut top = n.left.take().unwrap();
n.left = top.right.take();
top.right = Some(n);
return Some(top);
}
} else {
n.right = treap_insert(n.right.take(), key, priority);
if n.right.as_ref().unwrap().priority > n.priority {
let mut top = n.right.take().unwrap();
n.right = top.left.take();
top.left = Some(n);
return Some(top);
}
}
Some(n)
}
fn treap_delete(root: TreapLink, key: i32) -> TreapLink {
let Some(mut n) = root else {
return None;
};
if key == n.key {
return merge_treaps(n.left.take(), n.right.take());
}
if key < n.key {
n.left = treap_delete(n.left.take(), key);
} else {
n.right = treap_delete(n.right.take(), key);
}
Some(n)
}
fn treap_operations(ops: &[(bool, i32)]) -> Vec<i32> {
let mut root = None;
let mut random = 0xC0FFEE_u64;
for &(insert, key) in ops {
random ^= random << 13;
random ^= random >> 7;
random ^= random << 17;
root = if insert {
treap_insert(root, key, random)
} else {
treap_delete(root, key)
};
}
fn walk(root: &TreapLink, out: &mut Vec<i32>) {
if let Some(n) = root {
walk(&n.left, out);
out.push(n.key);
walk(&n.right, out);
}
}
let mut out = Vec::new();
walk(&root, &mut out);
out
}
fn main() {
let result = csv(treap_operations(&[
(true, 5),
(true, 2),
(true, 8),
(true, 1),
(false, 2),
]));
println!("{result}");
}
Complete std-only treap program for its typed teaching fixture. Parsing and output construction are separate from the core algorithm.
Try it
Compare the visible and independent fixtures. Explain the input assumption that makes this algorithm applicable, then identify a change that would invalidate it.
What success looks like: You can justify the choice from constraints rather than from a remembered problem title.
Check your understanding
Trace Randomized Treap on input insert2 insert2 insert1 inorder. Which result follows from the documented contract?
Reveal the answer
21,22,2
For this input the result is 1,2. BST order by key and heap order by priority. Compare this independent fixture with the worked trace: Insert 5,2,8,1, then delete 2. Rotations or merges preserve key order and priority order, so inorder returns 1,5,8. The demo uses reproducible pseudorandom priorities; expected logarithmic balance is a probabilistic assumption, not a worst-case guarantee.
Go deeper
Common misconception: “Two independent BST orders on the same keys”
BST order by key and heap order by priority. Insert 5,2,8,1, then delete 2. Rotations or merges preserve key order and priority order, so inorder returns 1,5,8. The demo uses reproducible pseudorandom priorities; expected logarithmic balance is a probabilistic assumption, not a worst-case guarantee.
- Concrete transition: Insert 5,2,8,1, then delete 2. Rotations or merges preserve key order and priority order, so inorder returns 1,5,8. The demo uses reproducible pseudorandom priorities; expected logarithmic balance is a probabilistic assumption, not a worst-case guarantee.
- Independent second fixture: Input
insert2 insert2 insert1 inorderproduces1,2. Execute the named function in the worked program with these typed arguments, then compare its actual result with this independently computed expectation. - Boundary and contract: Input
insert9 delete9 insert4 inorderproduces4. BST order by key and heap order by priority. The stated work bound is O(log n) expected operation · O(n) space. Count actual state changes; a successful output test alone does not prove that bound.
Transfer challenge: Compare the visible input insert5 insert2 insert8 insert1 delete2 inorder with insert3 insert1 insert5 delete3 inorder. Predict why their results are 1,5,8 and 1,5. Then change one legal value and explain whether the same invariant, bst order by key and heap order by priority, still applies.
Connections
- Randomized Treap: Mental Model: Keep BST order by key and heap order by random priority; insertion rotates a new node up and deletion merges its children.
- Challenge: Randomized Treap: Apply the space-separated insertN and deleteN tokens, then return the keys ascending at inorder. Keys form a set: inserting a present key and deleting an absent key change nothing.
Reveal the Algorithm Atlas answer
1,5,8
Learn this lesson with AI
Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.
I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools. Lesson: Randomized Treap: When to Use It (courseId "algorithms", lessonId "algorithm.treap.recognize") Link: https://crabrix.com/learn/algorithms/algorithm.treap.recognize Goal: BST order by key and heap order by priority. State the input preconditions before applying this invariant. Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.treap.recognize) and I will write the code there. Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.