Connected Components

Python data engineering interview problem. Difficulty: advanced. Pattern: Graphs. About 18 minutes. Part of the Pro drill bank.

Count connected components in an undirected graph. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.

A network can contain several separate groups of connected services. Count groups, not individual links. Nodes are numbered 0 to n - 1 and edges are undirected. Follow edges in both directions and count how many groups can reach one another. Write count_components(n: int, edges: list) -> int. With 5 nodes and edges [0, 1], [1, 2], [3, 4], nodes 0,1,2 form one group and 3,4 form another, so the answer is 2. The starter file already contains the function name, harness and print lines. Keep them and fill only the function body.

Requirements

  • Visit every node, including isolated nodes.
  • Treat each edge as usable in both directions.
  • Count each connected group once.

Constraints

  • Nodes are 0 to n - 1 and edges contain pairs of node ids.
  • Return an integer count.

Examples

Input: count_components(5, [[0, 1], [1, 2], [3, 4]]) Output: 2 Two components (and no isolate extras beyond those).

Topics: lakebench, python, union-find, components.

More Python interview questions · All interview problems · Learn data engineering

advanced

Connected Components

Interview-style drill: Count connected components in an undirected graph.

Implement `count_components(n: int, edges: list) -> int` for nodes `0..n-1`. Example: `5, [[0, 1], [1, 2], [3, 4]]` → `2`. Keep the harness.