~/problems / Graphs / DFS and connected components

Number of Connected Components in an Undirected Graph

easy ~15 min

An undirected graph has nodes 0 .. n-1 and a list of edges, where each edge [a, b] joins a and b. Two nodes are in the same component if you can walk from one to the other along edges.

Write count_components(n, edges) -> int: the number of connected components.

count_components(5, [[0, 1], [1, 2], [3, 4]])   # 2   {0, 1, 2} and {3, 4}
count_components(4, [])                         # 4   every node is alone
count_components(3, [[0, 1], [1, 0], [2, 2]])   # 2   repeated edges and self-loops are allowed

Constraints: 1 <= n <= 200_000, 0 <= len(edges) <= 200_000, 0 <= a, b < n. Edges may repeat, and an edge may join a node to itself.

Aim for O(n + len(edges)). One test is a path of 200,000 nodes, far beyond Python's recursion limit (about 1,000 frames), so avoid deep recursion.

Show hint

Every node you reach from a node you haven't seen yet belongs to one new component.

Topic: DFS and connected components. Iterative DFS / flood fill; count and label components.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc