Python 3D Academyবাংলা

Connected components and the redundant connection

🌍 In real life. An internet provider lays cables between houses one at a time. After each cable it wants to know: how many separate networks are there now? And if a new cable joins two houses that were already connected, it is redundant: it closes a loop and adds no new reach, so the provider could have saved it.

The idea in one sentence: feed every edge to union; each union that merges two groups joins two components, and each union that finds both ends already together is an edge that closes a cycle.

Its words:

  • connected component: a largest group of vertices that can all reach each other (Lesson 51.3)
  • redundant edge: an edge whose two ends are already connected; it closes a cycle
  • spanning: n vertices need exactly n − 1 useful edges to become one component; every extra edge is redundant

Step by step, for edges 0–1, 1–2, 3–4, 0–2 on five houses:

  1. start with 5 groups
  2. 0–1 merges: 4 groups; 1–2 merges: 3 groups; 3–4 merges: 2 groups
  3. 0–2: find(0) and find(2) give the same leader, so this edge is redundant: it closes the loop 0–1–2

Watch the last union find both ends already in one tree:

Why it works. Union-Find keeps exactly the components of the edges seen so far: an edge between two components joins them into one, and an edge inside a component changes nothing. That is why the number of groups is n minus the number of successful unions. An edge inside a component has another path between its ends already (that is what being in one component means), so together with that path it forms a cycle.

What it costs, by counting. One pass over the E edges, each a union of nearly constant cost (Lesson 53.2): O(V + E) in practice, and the edges can arrive one at a time. A graph search (Chapter 51) also counts components in O(V + E), but only for a graph you already have in full; adding one more edge means searching again.

class DSU:
    def __init__(self, n):
        self.parent = list(range(n))
        self.rank = [0] * n            # an upper bound on each tree's height
        self.groups = n

    def find(self, x):
        root = x
        while self.parent[root] != root:
            root = self.parent[root]
        while self.parent[x] != root:  # path compression: point the path at the leader
            nxt = self.parent[x]
            self.parent[x] = root
            x = nxt
        return root

    def union(self, a, b):
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False
        if self.rank[ra] < self.rank[rb]:
            ra, rb = rb, ra            # union by rank: the shorter tree goes under
        self.parent[rb] = ra
        if self.rank[ra] == self.rank[rb]:
            self.rank[ra] += 1
        self.groups -= 1
        return True

cables = [(0, 1), (1, 2), (3, 4), (0, 2), (2, 3)]
d = DSU(5)
for a, b in cables:
    if d.union(a, b):
        print(a, b, "joins two networks:", d.groups, "left")
    else:
        print(a, b, "is redundant: it closes a loop")

Mistakes and edge cases.

  • numbering from 1: many problems number vertices 1 to n; make the DSU size n + 1, or subtract 1 from every vertex
  • counting edges instead of merges: components = n − (successful unions), not n − (edges); a redundant edge merges nothing
  • isolated vertices: a vertex with no edges is still a component of its own; it is counted because the count starts at n
  • "the" redundant edge: a graph can have several; a problem that wants the last one in the input order should keep updating its answer rather than stopping at the first

Quiz

  1. What does this print?

    class DSU:
        def __init__(self, n):
            self.parent = list(range(n))
            self.rank = [0] * n            # an upper bound on each tree's height
            self.groups = n
    
        def find(self, x):
            root = x
            while self.parent[root] != root:
                root = self.parent[root]
            while self.parent[x] != root:  # path compression: point the path at the leader
                nxt = self.parent[x]
                self.parent[x] = root
                x = nxt
            return root
    
        def union(self, a, b):
            ra, rb = self.find(a), self.find(b)
            if ra == rb:
                return False
            if self.rank[ra] < self.rank[rb]:
                ra, rb = rb, ra            # union by rank: the shorter tree goes under
            self.parent[rb] = ra
            if self.rank[ra] == self.rank[rb]:
                self.rank[ra] += 1
            self.groups -= 1
            return True
    
    d = DSU(6)
    for a, b in [(0, 1), (1, 2), (3, 4)]:
        d.union(a, b)
    print(d.groups)
  2. Which edge does this report?

    class DSU:
        def __init__(self, n):
            self.parent = list(range(n))
            self.rank = [0] * n            # an upper bound on each tree's height
            self.groups = n
    
        def find(self, x):
            root = x
            while self.parent[root] != root:
                root = self.parent[root]
            while self.parent[x] != root:  # path compression: point the path at the leader
                nxt = self.parent[x]
                self.parent[x] = root
                x = nxt
            return root
    
        def union(self, a, b):
            ra, rb = self.find(a), self.find(b)
            if ra == rb:
                return False
            if self.rank[ra] < self.rank[rb]:
                ra, rb = rb, ra            # union by rank: the shorter tree goes under
            self.parent[rb] = ra
            if self.rank[ra] == self.rank[rb]:
                self.rank[ra] += 1
            self.groups -= 1
            return True
    
    d = DSU(4)
    for a, b in [(0, 1), (2, 3), (1, 2), (3, 0)]:
        if not d.union(a, b):
            print("redundant", a, b)
  3. A graph has 10 vertices and 12 edges, and is one component. How many of its edges are redundant?

    • 3: one component of 10 needs only 9 useful edges
    • 2
    • 0
  4. Edges keep arriving one at a time, and after each you must say how many networks there are. Which fits best?

    • Union-Find: each new edge is one union
    • A fresh BFS after every edge
    • Sorting the edges
  5. count_components(4, [(0, 1), (1, 0)]) returns 2, but it should be 3. Which line is wrong?

    def count_components(n, edges):
        d = DSU(n)
        for a, b in edges:
            d.union(a, b)
        return n - len(edges)

Coding tasks

  1. DSU is written for you. Write redundant_connection(edges): the vertices are numbered 1 to n, the edges are given as [a, b] lists, and the graph is a tree plus one extra edge. Return the edge (as given) that closes a cycle; if several could, return the one that comes last in edges.

  2. DSU is written for you. Write largest_group(n, pairs): n people numbered 0 to n − 1, and each pair are friends. Return how many people are in the biggest friend circle.