Example 1
- Input
- n = 5, edges = [[0,1],[1,2],[3,4]]
- Output
- 2
Nodes 0, 1 and 2 link together while nodes 3 and 4 form a second group.
Given a node count and undirected edges, count how many separate connected groups exist. Isolated nodes each count as their own group.
You are given n nodes labeled 0 to n - 1 and undirected edges with edges[i] = [a, b].
Return the number of connected components: maximal groups of mutually reachable nodes. A node with no edges forms a component of its own.
1 <= n <= 20000 <= edges.length <= 5000edges[i].length == 20 <= a, b < nNodes 0, 1 and 2 link together while nodes 3 and 4 form a second group.
The chain links every node, so the whole graph is a single component.
All four nodes are isolated, so each is its own connected component. Looking only at endpoints would miss every one.
The triangle contains one group, not three merges: its last edge closes a cycle. Nodes 3 and 4 make the other group, so the answer is 2.
A connected component contains all nodes reachable from one another. In Example 1, edges 0-1 and 1-2 join three nodes, while 3-4 joins a separate pair. Begin with five individual groups and let edges connect them: there are three genuine merges, leaving two groups. A cycle does not create a new merge once its endpoints are already connected, and a node absent from every edge must still be counted.
Reveal Label Propagation: intuition, complexity, and code
n and work down.n minus the component count, so count merges and subtract.Counting groups in undirected graphs is union-find home turf: merge each edge once and read the survivor count.