Python 3D Academyবাংলা

Union-Find or BFS: which to use

🌍 In real life. A messaging app keeps adding friendships all day, and every few seconds someone asks "can Ana's message reach Bo through friends?". A delivery company, on the other hand, has a fixed map and asks "what is the shortest route from the depot to this house?". The first is a stream of merges and yes-or-no questions; the second needs the route itself.

The idea in one sentence: use Union-Find when edges keep arriving and you only ask whether two things are connected (or how many groups there are); use BFS or DFS when you need a path, a distance or an order, or when edges can be removed.

Its words:

  • online: questions arrive between the changes, so each answer must reflect the graph as it is right now
  • offline: the whole graph is known before any question is asked
  • connectivity: only "same group or not", without the route between them

Step by step, an online stream on five people:

  1. union(0, 1), then ask about 1: its leader is 0
  2. union(2, 3), union(1, 2): now 0 to 3 are one group
  3. ask about 3: the leader is 0, so 3 and 0 are connected
  4. union(3, 0): already together, nothing to do

Each answer costs a few steps, however long the stream has been:

Why each tool wins where it does. Union-Find stores only who leads each group, not the edges, so it can't tell you a route, and it can't split a group when an edge is removed: once two leaders are linked, nothing remembers which edge did it. BFS keeps the whole graph and walks it, so it finds routes and distances (Lesson 51.2), and removing an edge just means walking without it. The price is that each question walks the graph again.

What it costs, by counting. Take 10,000 people, 10,000 friendships arriving one at a time, and a question after each.

  • Union-Find: each friendship and each question costs a few steps: roughly 20,000 operations in all
  • BFS per question: each question walks up to all the people and friendships so far, around 10,000 + 10,000 steps, and there are 10,000 questions: about 200,000,000 steps

For one question on a finished graph, both are about O(V + E), and BFS also gives the route.

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

events = [("union", 0, 1), ("ask", 0, 2), ("union", 1, 2), ("ask", 0, 2), ("union", 3, 4), ("ask", 2, 4)]
d = DSU(5)
for kind, a, b in events:
    if kind == "union":
        d.union(a, b)
    else:
        print(a, "and", b, "connected?", d.find(a) == d.find(b))

Mistakes and edge cases.

  • asking Union-Find for a route: it only knows leaders; if the question is "how", not "whether", search the graph
  • removing edges: Union-Find has no split; a common trick is to run the removals backwards as additions, when all the removals are known in advance
  • answering online questions with a search done at the start: the graph changes between questions, so a BFS made once goes out of date
  • a tree check: n vertices form a tree exactly when there are n − 1 edges and none of them is redundant; checking only the edge count misses a cycle plus a separate part

Quiz

  1. Which question needs BFS rather than Union-Find?

    • What is the fewest number of friends between Ana and Bo?
    • Are Ana and Bo connected through friends?
    • How many separate friend circles are there?
  2. Friendships can also end. Why does that hurt Union-Find?

    • It can't split a group: it doesn't remember which edge joined the leaders
    • It becomes too slow
    • It runs out of memory
  3. 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(4)
    answers = []
    for kind, a, b in [("ask", 0, 1), ("union", 0, 1), ("ask", 1, 0), ("union", 2, 3), ("ask", 0, 3)]:
        if kind == "union":
            d.union(a, b)
        else:
            answers.append(d.find(a) == d.find(b))
    print(answers)
  4. 4 vertices and 3 edges: 0–1, 1–2, 2–0. Is it a tree?

    • No: 2–0 closes a cycle and vertex 3 is cut off
    • Yes: it has n − 1 edges
    • Yes: every vertex has an edge
  5. is_tree(4, [(0, 1), (1, 2), (2, 0)]) returns True. Which line is wrong?

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

Coding tasks

  1. DSU is written for you. Write answer_queries(n, events): each event is ("union", a, b) or ("ask", a, b). Process them in order and return a list with one True/False per ask: whether a and b are connected at that moment.

  2. DSU is written for you. Write is_tree(n, edges): True if the n vertices (0 to n − 1) with these undirected edges form one tree: connected, with no cycle.