Sub topic 13
Extension: Undoing Unions with Rollback
This chapter assumes you know the DisjointSet class from earlier: parent array, union by size, and path compression. You should also be comfortable with stacks.
Why undo a union?
Standard union-find only merges. Some problems need to take a merge back. Examples:
- Searching a decision tree, where you union some elements, explore a branch, then return to try another branch.
- Offline dynamic connectivity, where edges appear and disappear over time and you answer connectivity queries as of a given moment.
Rollback union-find supports union and an undo that reverses the most recent successful union. It works as a stack: you can only undo the latest change first.
Why path compression has to go
Path compression rewrites parent pointers on every find, including pointers far from the last union. Reversing a union would then mean also reversing all of those rewrites. Tracking them is possible but costly, and it ruins the cost guarantees.
Union by size changes only two values per union: one parent pointer and one size. That is easy to reverse. So the rollback version keeps union by size and drops path compression.
What to record
Each successful union changes exactly three things:
parent[rb]goes fromrbtora.size[ra]grows bysize[rb].countdrops by one.
Pushing rb (the root that was attached) onto a history stack is enough to undo all three. Its parent is still ra, and its size has not changed since it was attached.
Implementation
class RollbackDisjointSet:
def __init__(self, n):
self.parent = list(range(n))
self.size = [1] * n
self.count = n
self.history = [] # roots that were attached, most recent last
def find(self, x):
while self.parent[x] != x: # no path compression
x = self.parent[x]
return x
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False
if self.size[ra] < self.size[rb]:
ra, rb = rb, ra
self.parent[rb] = ra
self.size[ra] += self.size[rb]
self.count -= 1
self.history.append(rb)
return True
def connected(self, a, b):
return self.find(a) == self.find(b)
def undo(self):
rb = self.history.pop()
ra = self.parent[rb]
self.size[ra] -= self.size[rb]
self.parent[rb] = rb
self.count += 1
def rollback_to(self, mark):
while len(self.history) > mark:
self.undo()
ds = RollbackDisjointSet(5)
ds.union(0, 1)
ds.union(2, 3)
mark = len(ds.history) # a checkpoint: 2 unions so far
ds.union(1, 3)
print(ds.connected(1, 3)) # True
print(ds.count) # 2
ds.rollback_to(mark)
print(ds.connected(1, 3)) # False
print(ds.count) # 3A checkpoint is just len(history). Rolling back to it undoes everything done since. Failed unions (same set) push nothing, so they never need undoing.
Cost
Union by size keeps every tree at depth O(log n). So find and union each cost O(log n) in the worst case, and undo costs O(1). This is slower than the near-constant amortized cost of the full version. You pay it for the ability to reverse changes.
Common mistakes
- Pushing history on a failed union, which makes
undodetach an unrelated root. - Forgetting to subtract the size on undo, which corrupts later size comparisons.
- Calling
undoon an empty history, which raisesIndexError.
Exercise
A rollback union-find with 4 elements runs union(0, 1), union(0, 1), union(2, 3), and then undo() once. What is count afterward, and which pairs are connected?
Show answer
The second union(0, 1) fails, so it pushes nothing. History holds two entries, and undo() removes the union(2, 3) link. Count started at 4, dropped to 3, dropped to 2, and returned to 3. Only 0 and 1 are connected.