Skip to content
DeepForgeby svx
All problems
HardGraph Algorithmsgraph-337

Union-Find Parent Writes

Problem

Count every assignment to the parent array during a sequence of union-find merges with path compression.

A find walks x to its root and then reassigns parent[y] = root for each node on the path except the root, counting one write per node even when the value is unchanged. A successful union then writes once more by attaching the second root to the first root. merges is a list of [a, b] pairs; return the total number of parent writes.

Hint

Compression writes only happen for nodes strictly below the root on the path.

Test cases

case 1
in: [4,[[0,1]]]
expected: 1
case 2
in: [4,[[0,1],[1,2]]]
expected: 3
case 3
in: [5,[[0,1],[1,2],[2,3]]]
expected: 5
case 4
in: [3,[[0,1],[0,1]]]
expected: 2
case 5
in: [2,[]]
expected: 0
Starter codePython
def union_find_parent_writes(n, merges):
    # Your code here
    pass

5 test cases · run your code against them in the editor