Python coding

Count the connected groups

There are n nodes numbered 0 to n - 1 and a list of undirected edges, each [a, b]. Two nodes are in the same group if a chain of edges joins them. Return the number of groups.

Edges may repeat, may join a node to itself and may close cycles; n may be 0.

Besides the tests, one large input (9,000 nodes) with a ~300 ms limit (scaled to your device's speed): brute force won't pass.

  • count_components(5, [[0,1],[1,2],[3,4]]) → 2
  • count_components(5, [[0,1],[1,2],[2,3],[3,4]]) → 1
  • count_components(4, []) → 4
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Use union-find: every node starts as its own group, so the count starts at n.

Hint 2

For each edge, find both roots. If they differ, hang one root under the other and subtract one; if they match, the edge changes nothing.

Hint 3

Keep find fast with path compression: point nodes closer to the root as you climb, and hang the smaller tree under the larger.

Solution and why it works
pythonO(n + E·α(n)), E = number of edges · O(n)
def count_components(n: int, edges: list[list[int]]) -> int:
    parent, size = list(range(n)), [1] * n

    def find(x: int) -> int:
        while parent[x] != x:
            parent[x] = parent[parent[x]]  # path halving, a one-pass path compression
            x = parent[x]
        return x

    groups = n
    for a, b in edges:
        ra, rb = find(a), find(b)
        if ra == rb:
            continue
        if size[ra] < size[rb]:
            ra, rb = rb, ra
        parent[rb] = ra
        size[ra] += size[rb]
        groups -= 1
    return groups

Each edge that joins two different roots merges two groups into one, so the answer is n minus the successful unions. An edge inside a group (a cycle, a repeat, a self-loop) merges nothing, which is why n - len(edges) is wrong. Compare find(a) with find(b), never parent[a] with parent[b]: a parent is not always the root. Path compression plus union by size make each operation near-constant amortized.