Union-find and connected components
Union-find maintains a partition of elements into disjoint components.
Its find operation returns a component representative, and union merges two components.
Use it for repeated connectivity queries as undirected edges arrive, including the cycle checks in Kruskal’s minimum spanning tree algorithm.
Read classes and graphs before this lesson.
The examples use an invented undirected graph with integer vertex labels.
Save the Python blocks in page order, or download the source below.
Run the script with uv run python union_find.py.
Represent components with parent links
Section titled “Represent components with parent links”Every vertex starts as its own component.
parent[item] identifies the next vertex toward its root, and a root points to itself.
Two vertices share a component exactly when their roots match.
The representative is an implementation choice; it need not be the smallest vertex label.
Union by size attaches the smaller component’s root to the larger component’s root.
Path compression makes every vertex visited by find point directly to the discovered root.
Only root entries in size describe current component sizes; entries for nonroots remain unused.
class UnionFind: """Maintain disjoint components with size-based unions and compression.
Attributes: parent: Parent index for each vertex; roots point to themselves. size: Component sizes, meaningful only at current roots. components: Current number of disjoint components. """
def __init__(self, count: int) -> None: """Create one component per vertex numbered from zero.
Args: count: Nonnegative number of vertices.
Raises: ValueError: If count is negative. """ if count < 0: raise ValueError("Vertex count must be nonnegative.") self.parent = list(range(count)) self.size = [1] * count self.components = count
def find(self, item: int) -> int: """Return the root and compress the path from item to that root.
Args: item: Vertex index in the half-open range [0, count).
Returns: The representative of the component containing item.
Raises: IndexError: If item is outside the vertex range. """ if not 0 <= item < len(self.parent): raise IndexError("Vertex index is out of range.") root = item while self.parent[root] != root: root = self.parent[root] while item != root: following = self.parent[item] self.parent[item] = root item = following return root
def union(self, left: int, right: int) -> bool: """Merge two components if they are currently distinct.
Args: left: One vertex index. right: Another vertex index.
Returns: True if two components merged, or False if already connected.
Raises: IndexError: If either index is outside the vertex range. """ left_root = self.find(left) right_root = self.find(right) if left_root == right_root: return False if self.size[left_root] < self.size[right_root]: left_root, right_root = right_root, left_root self.parent[right_root] = left_root self.size[left_root] += self.size[right_root] self.components -= 1 return True
groups = UnionFind(6)print("Initial parents:", groups.parent)print("Initial components:", groups.components)Initial parents: [0, 1, 2, 3, 4, 5]Initial components: 6The two find loops avoid recursive calls.
The first discovers the root, and the second changes links without changing component membership.
Save the next parent before overwriting a link, so the second loop can continue along the original path.
The explicit range check rejects negative indices, which Python lists would otherwise accept.
Count components as edges arrive
Section titled “Count components as edges arrive”Process each edge once and merge its two endpoint components. A merge reduces the component count by one. An edge within an existing component leaves the count unchanged, including a duplicate edge or a self-loop. Isolated vertices remain components even when they never occur in an edge.
edges = [(0, 1), (2, 3), (1, 2), (4, 5), (0, 2)]for left, right in edges: merged = groups.union(left, right) root_sizes = { item: groups.size[item] for item in range(len(groups.parent)) if groups.parent[item] == item } print("Edge:", (left, right), "Merged:", merged) print("Parents:", groups.parent) print("Root sizes:", root_sizes, "Components:", groups.components)
print("Before find(3):", groups.parent)print("Root of 3:", groups.find(3))print("After find(3):", groups.parent)print("Same component for 0 and 3:", groups.find(0) == groups.find(3))print("Same component for 0 and 5:", groups.find(0) == groups.find(5))Edge: (0, 1) Merged: TrueParents: [0, 0, 2, 3, 4, 5]Root sizes: {0: 2, 2: 1, 3: 1, 4: 1, 5: 1} Components: 5Edge: (2, 3) Merged: TrueParents: [0, 0, 2, 2, 4, 5]Root sizes: {0: 2, 2: 2, 4: 1, 5: 1} Components: 4Edge: (1, 2) Merged: TrueParents: [0, 0, 0, 2, 4, 5]Root sizes: {0: 4, 4: 1, 5: 1} Components: 3Edge: (4, 5) Merged: TrueParents: [0, 0, 0, 2, 4, 4]Root sizes: {0: 4, 4: 2} Components: 2Edge: (0, 2) Merged: FalseParents: [0, 0, 0, 2, 4, 4]Root sizes: {0: 4, 4: 2} Components: 2Before find(3): [0, 0, 0, 2, 4, 4]Root of 3: 0After find(3): [0, 0, 0, 0, 4, 4]Same component for 0 and 3: TrueSame component for 0 and 5: FalseAfter every edge, the parent trees represent exactly the graph’s connected components among edges processed so far. An edge between different trees creates one connected component from two, so attaching one root preserves this invariant. An edge inside one tree adds no new connection between components. Root sizes remain correct because only a successful merge adds one component’s size to another.
Never compare parent[left] with parent[right] to test connectivity.
Those immediate parents can differ while both vertices lead to the same root.
Call find on both vertices instead.
For a new edge in a simple undirected graph, a failed merge also signals that the edge closes a cycle.
def count_components(count: int, edges: list[tuple[int, int]]) -> int: """Count connected components in an undirected graph.
Args: count: Nonnegative number of vertices labeled from zero. edges: Endpoint pairs, including any duplicates or self-loops.
Returns: The number of connected components, including isolated vertices.
Raises: ValueError: If count is negative. IndexError: If an endpoint is outside the vertex range. """ groups = UnionFind(count) for left, right in edges: groups.union(left, right) return groups.components
for count, edges, expected in [ (0, [], 0), (1, [], 1), (4, [], 4), (4, [(0, 1), (1, 2)], 2), (3, [(0, 1), (1, 2), (2, 0)], 1), (3, [(0, 1), (0, 1), (2, 2)], 2),]: answer = count_components(count, edges) assert answer == expected print("Vertices:", count, "Edges:", edges, "Components:", answer)
for count, edges in [(-1, []), (3, [(-1, 0)]), (3, [(0, 3)])]: try: count_components(count, edges) except (ValueError, IndexError) as error: print(type(error).__name__, str(error))Vertices: 0 Edges: [] Components: 0Vertices: 1 Edges: [] Components: 1Vertices: 4 Edges: [] Components: 4Vertices: 4 Edges: [(0, 1), (1, 2)] Components: 2Vertices: 3 Edges: [(0, 1), (1, 2), (2, 0)] Components: 1Vertices: 3 Edges: [(0, 1), (0, 1), (2, 2)] Components: 2ValueError Vertex count must be nonnegative.IndexError Vertex index is out of range.IndexError Vertex index is out of range.Explain the cost
Section titled “Explain the cost”Initialization takes O(n) time and O(n) space for n vertices.
Union by size limits tree height to O(log n), since a vertex’s component size at least doubles whenever a merge increases its depth.
Path compression shortens later searches.
Together, the two techniques give O(α(n)) amortized time per find or union, where α is the inverse Ackermann function.
The bound describes a sequence of operations, not constant worst-case time for every call.
An individual call can still take O(log n).
For e edges, component counting takes O(n + e α(n)) total time and O(n) auxiliary space.
These bounds assume constant-time operations on vertex indices and sizes.
The trace scans all vertices after each edge, adding O(ne) display work that count_components does not perform.
Use breadth-first or depth-first search when a static graph also requires an actual path or a component traversal. This union-find structure does not store graph paths and cannot split a component when an edge disappears. Its parent links describe the data structure; they need not correspond to original graph edges.
Practice
Section titled “Practice”- Solve Redundant Connection by inspecting failed merges. Convert its vertex labels carefully because that problem starts labels at one.
- Solve Number of Provinces by merging connected cities. Compare the matrix scan cost with the cost of the union operations.
Download the Python source to run the complete example locally.
Further reading
Section titled “Further reading”Carnegie Mellon’s union-find lecture develops union by size, path compression, and their amortized analysis. It explains the assumptions behind the inverse Ackermann bound.
Python’s class tutorial explains instance attributes and method calls. Those features hold the parent arrays and component count together here.