Advanced Data Structures · 15 min · free lesson

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.

Core idea

BST order by key and heap order by priority. 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.

Algorithm Atlas · worked example

See the algorithm, step by step

On your device

Keep BST order by key and heap order by random priority; insertion rotates a new node up and deletion merges its children.

O(log n) expected operation · O(n) space57 execution steps
main · before line 100Initialize a local value

This call is starting. Local values appear as they are initialized.

Data & variables

Changed Source index
Example inputinsert4 insert2 delete4 inorder

Follow the code. Data appears here when it enters scope.

Call stack · 1 frame
  1. maincall 1

Rust source

Line 100
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, 4), (true, 2), (false, 4)]));
    println!("{result}");
}

Try your own version

Change the independent fixture `insert4 insert2 delete4 inorder` in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge `insert5 insert2 insert8 insert1 delete2 inorder`.

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.

Recorded from this Rust example and checked against its original output. Playback runs locally in your browser. Values show the state before the highlighted line. Borrowed or moved values are hidden when they cannot be inspected safely.
Five-panel Advanced Data Structures infographic; panel 4 illustrates Treap.
Treap: follow panel 4 to see the operation, then trace this lesson's example.

Understand it

BST order by key and heap order by priority. The worked program demonstrates this invariant on an independent fixture, so you can study the implementation before predicting the challenge result.

For teaching input insert4 insert2 delete4 inorder, the worked program returns 2. Its functions are complete and use only std. Adapt the same state transitions to the visible challenge input insert5 insert2 insert8 insert1 delete2 inorder; predict that result before opening the answer reveal. The precise 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.

Return canonical output: lowercase booleans, decimal integers without leading zeros, comma-separated values and semicolon-separated groups, with no extra whitespace or final newline. Whole medians use integer form and half medians use .5. Textual sentinels such as none and # retain their stated meaning. String and character-grid fixtures use ASCII unless the lesson explicitly specifies Unicode scalar values.

Solve the exact task, not just the visible example: 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. On input insert5 insert2 insert8 insert1 delete2 inorder, predict the output before opening the answer reveal. The revealed output is a test oracle for this case, while private checks exercise other legal cases. Start by stating the input grammar and output format in your own words. Parse the complete input, including surrounding whitespace, before relying on any convenient positions in the example.

Build the solution around one maintained claim: Keep BST order by key and heap order by random priority; insertion rotates a new node up and deletion merges its children. Decide what state represents that claim, how it is initialized, what a single update does, and when the algorithm stops. An advanced structure or offline query order packages an invariant across operations. Name what each node, block, or reordered query state stores. Trace the visible input by hand and record at least two intermediate states, not only the final answer. If the trace cannot justify your predicted output, there is a gap between the idea and the implementation.

Check both correctness and cost. The intended bound is O(log n) expected operation · O(n) space; explain which operation dominates it and how many times the input can trigger that operation. Test empty ranges, repeated updates, undo operations where supported, and the exact boundary between adjacent blocks. Add one small case that should succeed, one boundary case, and one case chosen to challenge the invariant. Compare your hand result with the program's result, then use a failing case to fix the earliest incorrect state transition rather than patching the final output.

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, 4), (true, 2), (false, 4)]));
    println!("{result}");
}

Complete std-only treap program for its typed teaching fixture. Parsing and output construction are separate from the core algorithm.

Practice starter

pub fn solve(input: &str) -> String {
    // 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.
    // Trim surrounding whitespace; implement parsing and the algorithm.
    let _ = input;
    todo!("implement treap")
}

Try it

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.

What success looks like: The private harness prints PASS treap. It checks at least five distinct semantic inputs plus surrounding-whitespace variants. Explain complexity separately; this harness does not time the algorithm.

Check your understanding

Boundary check for treap: with input insert9 delete9 insert4 inorder, what result should solve return?

Reveal the answer
  1. 4
  2. 5
  3. 3

For this input the result is 4. 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. The independent teaching fixture demonstrates this rule; predict the separate visible challenge before revealing its answer.

  1. Pattern-specific invariant: BST order by key and heap order by priority. This is the property the named implementation maintains; explain which comparison, state update or recursive return in the worked program establishes it.
  2. Independent typed fixture: The worked call uses insert4 insert2 delete4 inorder and computes 2. Keep parsing separate, then identify the core state before and after this call.
  3. Different legal case: For insert9 delete9 insert4 inorder, the independently calculated result is 4. The complexity discussion uses O(log n) expected operation · O(n) space. Verify the state invariant before reasoning about the operation count.

Transfer challenge: Change the independent fixture insert4 insert2 delete4 inorder in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge insert5 insert2 insert8 insert1 delete2 inorder.

Connections

  • Randomized Treap: When to Use It: ordered sets with expected logarithmic operations
  • Skip List: Mental Model: Promote nodes randomly into sparse express lanes and descend when the next jump overshoots.
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: Challenge: Randomized Treap (courseId "algorithms", lessonId "algorithm.treap.challenge")
Link: https://crabrix.com/learn/algorithms/algorithm.treap.challenge
Goal: BST order by key and heap order by priority. 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.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.treap.challenge) 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.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.