Disjoint Sets Basics
Step 1 of 8
parent
0→01→12→23→34→45→5
Six elements, each its own parent. That is six separate groups, before anything is joined.
The Idea
Keep one array: parent[x] is who x points at. Follow the pointers and you stop at an element that points at itself — the root, which is the group's name.
find walks up to that root. union finds both roots and hangs one under the other, merging two groups with a single write.
Real-World Example
A photo library clustering faces. When you confirm two clusters are the same person it does not relabel every photo — it points one cluster at the other. Asking "same person?" later just compares the two labels you arrive at.
The Code
Your turn
Fill in the blank.
parent = [0, 0, 2, 2]
def find(x):
while parent[x] ___ x:
x = parent[x]
return x
print(find(1), find(3)) # 0 2Mini quiz
1 / 3