CodingNodes / Graphs / Number of Connected Components In An Undirected Graph System design Space play · ←→ step · R restart

Problem

There are n nodes, numbered 0 to n - 1, and a list edges where each pair [a, b] is an undirected edge between nodes a and b.

A connected component is a group of nodes where every node can reach every other node of the group through edges, and no node of the group is joined to a node outside it. Return the number of connected components.

Constraints

  • 1 ≤ n ≤ 2000
  • 0 ≤ edges.length ≤ 5000
  • 0 ≤ a, b < n and a ≠ b; no edge is listed twice

Examples: pick one to animate

Solutions

TimeO((n + e) · α(n)) SpaceO(n)

Time: Each of the e edges does two finds and at most one merge. With union by size and path halving each costs almost constant time (the inverse Ackermann function α). Setting up the arrays costs O(n).

Space: The parent and size arrays hold one number per node.

Start with every node in a set of its own, so there are n components. Go through the edges: if the two ends have different roots, the edge joins two components, so merge the sets and subtract one from the count. If the roots are the same the edge adds nothing (it only closes a circle). What is left in count at the end is the number of components. Union by size and path halving keep the trees shallow.