Union-Find (Disjoint Set)

Step 1: Union-Find (Disjoint Set)

A Minimum Spanning Tree (MST) connects every node in a network at the least total cost. Both classic MST algorithms lean on a Union-Find (Disjoint Set Union, or DSU) structure to track which nodes are already linked, so we build it first.

Implement two methods on the provided DSU class:

  • find(x): return the representative (root) of the set containing x, applying path compression so future lookups are fast.
  • union(a, b): merge the sets of a and b using union by rank (attach the shorter tree under the taller one). Return True if a merge happened, or False if a and b were already in the same set.

The connected(a, b) helper is already written for you in terms of find.

Real use: when laying fiber between towns, DSU instantly answers "are these two already on the same network?" so you never add a redundant, money-wasting cable.

Hints
Starter code
class DSU:
    def __init__(self, n):
        self.parent = list(range(n))
        self.rank = [0] * n

    def find(self, x):
        """Return the representative (root) of x, using path compression."""
        # TODO: follow parent pointers up to the root, compressing the path
        pass

    def union(self, a, b):
        """Merge the sets of a and b by rank. Return True if merged, False if already joined."""
        # TODO: find both roots; if equal return False; else attach shorter under taller
        pass

    def connected(self, a, b):
        return self.find(a) == self.find(b)
Write it on a laptop

The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.