Python 3D Academyবাংলা

Groups that merge: find and union

🌍 In real life. On the first day of school nobody knows anybody: every student is a friend circle of one. Then Ana befriends Bo, Cy befriends Di, and Bo befriends Di, so suddenly Ana, Bo, Cy and Di are all one circle. Two questions keep coming up: "are these two in the same circle?" and "merge these two circles".

A graph search (Chapter 51) can answer the first question, but it walks the whole circle every time. Union-Find (also called a disjoint set union, DSU) answers both questions with a few steps each, while friendships keep arriving.

The idea in one sentence: each group is a small tree with a leader at its root; find(x) follows parent links up to the leader, and union(a, b) hangs one leader under the other.

Its words:

  • parent: a list where parent[i] is the item i points to; a leader points to itself
  • leader (root, representative): the item at the top of a group's tree; two items are in the same group exactly when they have the same leader
  • find(x): follow parent from x until an item is its own parent
  • union(a, b): find both leaders; if they differ, make one the parent of the other

Step by step, for six students 0 to 5:

  1. start with parent = [0, 1, 2, 3, 4, 5]: everyone leads a group of one
  2. union(0, 1): leaders 0 and 1 differ, so parent[1] = 0
  3. union(2, 3): parent[3] = 2
  4. union(1, 3): 1's leader is 0 and 3's is 2, so parent[2] = 0; now 0, 1, 2 and 3 are one group
  5. find(3) walks 3 → 2 → 0: the leader is 0

Watch the forest grow, and the parent list underneath change with it:

Why it works. Every item has exactly one parent, and following parents always ends at a leader, because a union only ever points a leader at something else: no loops can form. Two items share a leader exactly when unions joined them, directly or through others, because union links whole trees: everything under rb now also leads up to ra. So "same group?" is just find(a) == find(b).

What it costs, by counting. A union costs two finds plus one assignment. A find costs one step per parent link, and that is the weak spot: without care a tree can become a chain. Joining 0..n−1 as union(1, 0), union(2, 1), … makes each new leader the parent of the old one, so find(0) walks the whole chain: for 1,000 items that is 999 links, and asking it 1,000 times costs about a million steps. Lesson 53.2 fixes this with two small tricks.

def find(parent, x):
    while parent[x] != x:          # walk up until an item is its own parent
        x = parent[x]
    return x                       # the leader

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

parent = list(range(6))
for a, b in [(0, 1), (2, 3), (1, 3), (4, 5)]:
    union(parent, a, b)
print(parent)
print(find(parent, 3), find(parent, 5))
print("same circle?", find(parent, 1) == find(parent, 2), find(parent, 0) == find(parent, 4))

Mistakes and edge cases.

  • linking the items instead of their leaders: parent[b] = a cuts b out of its old tree and leaves the rest of that group behind; always link find(b) under find(a)
  • comparing parents instead of leaders: parent[a] == parent[b] misses items deeper in the same tree; compare find(a) == find(b)
  • a union of an item with itself, or of two already joined: both leaders are the same, so nothing should change; return early
  • counting groups: start with n and take one away for each union that really merged two groups

Quiz

  1. What does this print?

    def find(parent, x):
        while parent[x] != x:          # walk up until an item is its own parent
            x = parent[x]
        return x                       # the leader
    
    def union(parent, a, b):
        ra, rb = find(parent, a), find(parent, b)
        if ra == rb:
            return False               # already one group
        parent[rb] = ra                # hang b's leader under a's
        return True
    
    parent = [0, 0, 1, 3]
    print(find(parent, 2), find(parent, 3))
  2. What does this print?

    def find(parent, x):
        while parent[x] != x:          # walk up until an item is its own parent
            x = parent[x]
        return x                       # the leader
    
    def union(parent, a, b):
        ra, rb = find(parent, a), find(parent, b)
        if ra == rb:
            return False               # already one group
        parent[rb] = ra                # hang b's leader under a's
        return True
    
    parent = list(range(4))
    union(parent, 0, 1)
    union(parent, 2, 3)
    print(union(parent, 1, 3), union(parent, 0, 2), parent)
  3. How do you check whether a and b are in the same group?

    • find(parent, a) == find(parent, b)
    • parent[a] == parent[b]
    • a == b
  4. Items 0..999 are joined by union(1, 0), union(2, 1), …, union(999, 998). How many parent links does find(0) follow?

    • 999: the tree has become a chain
    • 1
    • about 10
  5. After union(parent, 2, 0), items 0 and 1 should stay together, but 1 is left on its own. Which line is wrong?

    def union(parent, a, b):
        ra = find(parent, a)
        if ra == find(parent, b):
            return False
        parent[b] = ra
        return True

Coding tasks

  1. Write find(parent, x): follow the parent links from x and return the leader, the item that is its own parent.

  2. find is written for you. Write union(parent, a, b): if a and b have different leaders, hang b's leader under a's and return True; otherwise change nothing and return False.

  3. Friend circles. Write count_groups(n, pairs): n students are numbered 0 to n − 1, and each pair (a, b) in pairs are friends. Return how many separate friend circles there are.