awelgorithms

Find returns the representative

Updated

find(x) walks parent until it reaches a root and returns that index. The representative is the root, not an arbitrary member of the set.

What to focus on

After unions, a child and a root can share a representative even when parent[child] is not the child. Return the root, not the first parent hop.

Worked examples

child

a = [0, 1, 2, 3], parent=[0,0,2,3], find(1)
  1. 1 → 0
  2. 0 is a root

Result: 0

already root

a = [0, 1, 2, 3], parent=[0,1,2,3], find(2)
  1. parent[2]=2

Result: 2

one index

a = [0], parent=[0], find(0)
  1. only root

Result: 0

Try it

Write find(parent, x). parent is the parent array. x is the index whose representative you want. Walk parent until you reach a root (parent[i] = i). Return that root index. parent=[0, 0, 2, 3], find(1) → 0. parent=[0, 1, 2, 3], find(2) → 2. parent=[0], find(0) → 0.

x is a live index in 0..n-1. Every parent[i] is a valid index. The forest is already built.