Advanced Data Structures · 15 min · free lesson

Challenge: Rollback DSU

Apply unions and checkpoint operations, then answer the connectivity query after rollback.

Core idea

Every parent change would need to be recorded to undo it. Apply unions and checkpoint operations, then answer the connectivity query after rollback.

Algorithm Atlas · worked example

See the algorithm, step by step

On your device

Record every parent or size mutation so recursion over time can undo unions without path compression.

O(log n) union/find typical · O(changes) history50 execution steps
main · before line 62Initialize a local value

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

Data & variables

Changed Source index
Example inputn=3 unions=(0,1) checkpoint union=(1,2) rollback query=(0,1)

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

Call stack · 1 frame
  1. maincall 1

Rust source

Line 62
struct RollbackDsu {
    parent: Vec<usize>,
    size: Vec<usize>,
    history: Vec<(usize, usize, usize)>,
}
impl RollbackDsu {
    fn new(n: usize) -> Self {
        Self {
            parent: (0..n).collect(),
            size: vec![1; n],
            history: Vec::new(),
        }
    }
    fn root(&self, mut v: usize) -> usize {
        while v != self.parent[v] {
            v = self.parent[v];
        }
        v
    }
    fn join(&mut self, a: usize, b: usize) {
        let (mut a, mut b) = (self.root(a), self.root(b));
        if a == b {
            return;
        }
        if self.size[a] < self.size[b] {
            std::mem::swap(&mut a, &mut b);
        }
        self.history.push((b, a, self.size[a]));
        self.parent[b] = a;
        self.size[a] += self.size[b];
    }
    fn checkpoint(&self) -> usize {
        self.history.len()
    }
    fn rollback(&mut self, mark: usize) {
        while self.history.len() > mark {
            let (b, a, size) = self.history.pop().unwrap();
            self.parent[b] = b;
            self.size[a] = size;
        }
    }
}
fn rollback_query(
    n: usize,
    before: &[(usize, usize)],
    after: &[(usize, usize)],
    query: (usize, usize),
) -> bool {
    let mut dsu = RollbackDsu::new(n);
    for &(a, b) in before {
        dsu.join(a, b);
    }
    let mark = dsu.checkpoint();
    for &(a, b) in after {
        dsu.join(a, b);
    }
    dsu.rollback(mark);
    dsu.root(query.0) == dsu.root(query.1)
}
 
fn main() {
    let result = rollback_query(3, &[(0, 1)], &[(1, 2)], (0, 1)).to_string();
    println!("{result}");
}

Try your own version

Change the independent fixture `n=3 unions=(0,1) checkpoint union=(1,2) rollback query=(0,1)` in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge `n=4 unions=(0,1),(1,2) checkpoint union=(2,3) rollback query=(0,3)`.

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.
Five-panel Advanced Data Structures infographic; panel 1 illustrates Dsu Rollback.
Dsu Rollback: follow panel 1 to see the operation, then trace this lesson's example.

Understand it

Every parent change would need to be recorded to undo it. The worked program demonstrates this invariant on an independent fixture, so you can study the implementation before predicting the challenge result.

For teaching input n=3 unions=(0,1) checkpoint union=(1,2) rollback query=(0,1), the worked program returns true. Its functions are complete and use only std. Adapt the same state transitions to the visible challenge input n=4 unions=(0,1),(1,2) checkpoint union=(2,3) rollback query=(0,3); predict that result before opening the answer reveal. The precise contract is: Apply unions and checkpoint operations, then answer the connectivity query after rollback.

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 unions and checkpoint operations, then answer the connectivity query after rollback. On input n=4 unions=(0,1),(1,2) checkpoint union=(2,3) rollback query=(0,3), 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: Record every parent or size mutation so recursion over time can undo unions without path compression. 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) union/find typical · O(changes) history; 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

Record every parent or size mutation so recursion over time can undo unions without path compression.

When to use it: offline dynamic connectivity and divide-over-time

Complexity: O(log n) union/find typical · O(changes) history

Input: n=4 unions=(0,1),(1,2) checkpoint union=(2,3) rollback query=(0,3)

Read the code

struct RollbackDsu {
    parent: Vec<usize>,
    size: Vec<usize>,
    history: Vec<(usize, usize, usize)>,
}
impl RollbackDsu {
    fn new(n: usize) -> Self {
        Self {
            parent: (0..n).collect(),
            size: vec![1; n],
            history: Vec::new(),
        }
    }
    fn root(&self, mut v: usize) -> usize {
        while v != self.parent[v] {
            v = self.parent[v];
        }
        v
    }
    fn join(&mut self, a: usize, b: usize) {
        let (mut a, mut b) = (self.root(a), self.root(b));
        if a == b {
            return;
        }
        if self.size[a] < self.size[b] {
            std::mem::swap(&mut a, &mut b);
        }
        self.history.push((b, a, self.size[a]));
        self.parent[b] = a;
        self.size[a] += self.size[b];
    }
    fn checkpoint(&self) -> usize {
        self.history.len()
    }
    fn rollback(&mut self, mark: usize) {
        while self.history.len() > mark {
            let (b, a, size) = self.history.pop().unwrap();
            self.parent[b] = b;
            self.size[a] = size;
        }
    }
}
fn rollback_query(
    n: usize,
    before: &[(usize, usize)],
    after: &[(usize, usize)],
    query: (usize, usize),
) -> bool {
    let mut dsu = RollbackDsu::new(n);
    for &(a, b) in before {
        dsu.join(a, b);
    }
    let mark = dsu.checkpoint();
    for &(a, b) in after {
        dsu.join(a, b);
    }
    dsu.rollback(mark);
    dsu.root(query.0) == dsu.root(query.1)
}

fn main() {
    let result = rollback_query(3, &[(0, 1)], &[(1, 2)], (0, 1)).to_string();
    println!("{result}");
}

Complete std-only dsu-rollback 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 unions and checkpoint operations, then answer the connectivity query after rollback.
    // Trim surrounding whitespace; implement parsing and the algorithm.
    let _ = input;
    todo!("implement dsu-rollback")
}

Try it

Apply unions and checkpoint operations, then answer the connectivity query after rollback.

What success looks like: The private harness prints PASS dsu-rollback. 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 dsu-rollback: with input n=3 unions=(0,1),(1,2) checkpoint union=(0,2) rollback query=(0,2), what result should solve return?

Reveal the answer
  1. true
  2. false
  3. The valid input necessarily panics

For this input the result is true. Every parent change would need to be recorded to undo it. Compare this independent fixture with the worked trace: Build (0,1),(1,2), mark the history length, then join (2,3). Rolling back pops that last union and restores sizes and the separated root. Query (0,3) is false again, while (0,2) remains connected.

Go deeper

Common misconception: “Union by size cannot work without compression”

Every parent change would need to be recorded to undo it. The independent teaching fixture demonstrates this rule; predict the separate visible challenge before revealing its answer.

  1. Pattern-specific invariant: Every parent change would need to be recorded to undo it. 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 n=3 unions=(0,1) checkpoint union=(1,2) rollback query=(0,1) and computes true. Keep parsing separate, then identify the core state before and after this call.
  3. Different legal case: For n=3 unions=(0,1),(1,2) checkpoint union=(0,2) rollback query=(0,2), the independently calculated result is true. The complexity discussion uses O(log n) union/find typical · O(changes) history. Verify the state invariant before reasoning about the operation count.

Transfer challenge: Change the independent fixture n=3 unions=(0,1) checkpoint union=(1,2) rollback query=(0,1) in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge n=4 unions=(0,1),(1,2) checkpoint union=(2,3) rollback query=(0,3).

Connections

  • Rollback DSU: When to Use It: offline dynamic connectivity and divide-over-time
  • Mo's Algorithm: Mental Model: Order offline range queries so adjacent queries move their boundaries only a small distance.
Reveal the Algorithm Atlas answer

false

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: Rollback DSU (courseId "algorithms", lessonId "algorithm.dsu-rollback.challenge")
Link: https://crabrix.com/learn/algorithms/algorithm.dsu-rollback.challenge
Goal: Every parent change would need to be recorded to undo it. Apply unions and checkpoint operations, then answer the connectivity query after rollback.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.dsu-rollback.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.