Complete the code to find the root parent of a node with path compression.
def find(parent, x): if parent[x] != x: parent[x] = [1] # Path compression step return parent[x]
The path compression step recursively finds the root parent and updates the parent of x to point directly to the root.
Complete the union function to merge two sets by their root parents.
def union(parent, x, y): rootX = find(parent, x) rootY = find(parent, y) if rootX != rootY: parent[[1]] = rootY
We set the parent of rootX to rootY to merge the two sets.
Fix the error in the find function to correctly implement path compression.
def find(parent, x): if parent[x] != x: [1] # Fix this line return parent[x]
The correct path compression updates parent[x] to the root found by recursively calling find on parent[x].
Fill both blanks to create a dictionary comprehension that maps each node to its root parent.
root_map = {node: [1] for node in nodes if [2]We map each node to its root parent using find, and include only nodes present in parent.
Fill all three blanks to create a union-find initialization with path compression and union operations.
parent = {node: [1] for node in nodes}
def find(parent, x):
if parent[x] != x:
parent[x] = [2]
return parent[x]
def union(parent, x, y):
rootX = find(parent, x)
rootY = find(parent, y)
if rootX != rootY:
parent[[3]] = rootYInitialize each node as its own parent, compress paths by updating parent[x] to the root, and union by setting parent of rootX to rootY.
