Practice · Union-find · 1 of 2

Count Connected Groups

There are n nodes, numbered from 0 to n − 1, and a list edges where each [a, b] joins nodes a and b (edges have no direction). Two nodes are in the same group if you can get from one to the other along edges.

Return the number of groups (the connected components). A node with no edges is a group on its own.

Example 1

Input
n = 6, edges = [[0, 3], [3, 4], [1, 5]]
Output
3
The groups are {0, 3, 4}, {1, 5}, and node 2 on its own.

Example 2

Input
n = 4, edges = [[0, 1], [1, 2], [2, 0], [2, 3]]
Output
1
The loop 0–1–2 doesn't split anything off, and 3 hangs off 2: one group.

Constraints

  • 1 ≤ n ≤ 2000
  • edges holds 0 to 5000 edges. Each joins two different nodes, and no edge is listed twice.
Brush up firstUnion-Find visualiser