Build a Union-Find That Can Undo Its Most Recent Merges
Last updated: November 29, 2026
Quick Overview
Design a disjoint set structure over n elements supporting union, find, the current number of components, undo of the most recent union, and rollback to a saved snapshot, with every operation in O(log n).
0
0
0 solved
Design a disjoint set structure over n elements supporting union, find, the current number of components, undo of the most recent union, and rollback to a saved snapshot, with every operation in O(log n).
Rollback union-find is the building block for offline dynamic connectivity and backtracking search, and Google technical screens sometimes go here after a basic union-find warm-up. The interviewer checks that you know path compression breaks undo, that union by size alone keeps finds logarithmic, and that no-op unions still need history entries.
What the Interviewer Expects
- Explains why path compression is incompatible with exact undo
- Uses union by size to bound tree height by log n
- Records each union on a history stack
- Pushes a marker for no-op unions so undo stays aligned
- Implements snapshot and rollback as stack depth
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Use this to solve offline dynamic connectivity with edge deletions via a segment tree over time.
- How would you make the history persistent so old versions can be queried?
- What does undo cost if you also maintain component sums?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Operations:
union(a, b),find(x),components,undo(),snapshot(),rollback(snap). - Undo reverts exactly the last union call, including calls that merged nothing.
- Worst-case O(log n) p...
High-Level Design
Path compression rewires many pointers during a find, so undoing a union would require undoing those rewires too. Drop it. Union by size still guarantees tree height at most log2(n), because a node's ...