Number of Connected Components in an Undirected Graph

Medium Graphs

There are n nodes, numbered 0 to n - 1, and edges lists undirected links between them: an [a, b] pair joins nodes a and b, and a link works in both directions.

Two nodes are in the same component when a path of edges leads from one to the other; a node with no edges is a component on its own.

Return the number of components.

Example 1

Input: n = 6, edges = [[0,1],[1,2],[2,0],[4,5]]
Output: 3

Nodes 0, 1 and 2 are joined, 4 and 5 are joined, and 3 is alone.

Example 2

Input: n = 4, edges = [[3,1],[0,1],[2,3]]
Output: 1

Example 3

Input: n = 3, edges = []
Output: 3

Constraints

  • 1 ≤ n ≤ 10⁵
  • 0 ≤ edges.length ≤ 10⁵
  • 0 ≤ a, b < n and a ≠ b for every edge [a, b]
  • no two edges join the same pair of nodes, in either order

More Graphs

All Graphs problems