Skip to content
BytePatterns

Disjoint Sets Basics

Union-Find: lesson 1 of 4

Every group is named by one root, and find walks up to it.

Lesson 1 of 4 · 5 min

Disjoint Sets Basics

Step 1 of 8

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

parent = list(range(6))          # everyone starts alone: parent[i] == i
def find(x):
    while parent[x] != x:        # walk up to the root
        x = parent[x]
    return x

def union(a, b):
    ra, rb = find(a), find(b)
    if ra == rb: return False    # already one group
    parent[ra] = rb              # hang one root under the other
    return True

union(0, 1); union(1, 2)
print(find(0) == find(2), find(0) == find(3))

Python

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 2

Mini quiz

1 / 3

How is the root of a group recognised?

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.