Skip to content

Connected Components in a Graph

MediumGraphs
Decode it first. Clues, constraints, pattern and plan before any code.

You have n nodes labelled 0 to n - 1 and a list of undirected edges, where [a, b] joins a and b. Return the number of connected components: groups of nodes where every node can reach every other through edges.

n = 5, edges = [[0, 1], [1, 2], [3, 4]]  →  2   ({0,1,2} and {3,4})
n = 3, edges = []                        →  3   (every node is alone)

Constraints

  • 1 <= n <= 2000
  • 0 <= edges.length <= 5000
  • 0 <= a, b < n and a != b