Skip to content
mlmentorship

Number of Connected Components

Launch one flood per uncovered undirected component, retain isolated vertices, and reuse the component sizes to count unreachable pairs.

Published · 24 min read ·Core ·Mixed

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Number of Connected Components

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A nonnegative node_count and undirected edge pairs with integer endpoints from 0 through node_count - 1. Output. Return the number of connected components among all declared vertices. Rules. Vertices belong together if an undirected path connects them, directly or through other vertices. Every isolated vertex forms its own component. Repeated edges and self-loops do not merge additional components. Preserve the inputs. Zero vertices returns zero. Example. Five vertices and edges [[0, 1], [1, 2], [3, 4]] return 2. The components are {0, 1, 2} and {3, 4}; six vertices without edges return 6.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Each unseen outer-loop vertex starts exactly one DFS and marks exactly one previously uncounted connected component.

Problem trace

Count new traversals, not every node reached within them

Input and goalCount separate groups in an undirected graph.
Build the graph and initializeBuild both directions for edges 0-1, 0-2 and 3-4. Node five has no neighbors. Start with seen={}, components=0.
012345
seen{}
Original undirected adjacency lists
012
10
20
34
43
5none
stack: top at rightempty
edgeTopology0-1, 0-2, 3-4; node 5 isolatedrowMeaningrow index = node; cells = adjacent nodesadjacency0:[1,2]; 1:[0]; 2:[0]; 3:[4]; 4:[3]; 5:[]seenState{}components0
queue
[]
edge topology
0-1, 0-2, 3-4; node 5 isolated
row meaning
row index = node; cells = adjacent nodes

Recognize it
Use it when an undirected graph may contain multiple disconnected groups, including isolated vertices, and the task asks how many maximal reachable groups exist.
Keep true
After processing outer-loop starts below the current index, every vertex in their components is seen and components equals the number of DFS launches. A seen vertex can never launch another count.
Reuse it
A global visited set partitions a graph: every new search root contributes one component and consumes all vertices that must not contribute again. This transfers to islands, provinces, and cluster counting.
Build both directions for edges 0-1, 0-2 and 3-4. Node five has no neighbors. Start with seen={}, components=0. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does visiting nodes 1 and 2 not add components, while visiting isolated node 5 does?
Full interview answer 24 min read

Count the separate connected groups in an undirected graph, including vertices that have no edges.

Problem

Input. A nonnegative node_count and undirected edge pairs with integer endpoints from 0 through node_count - 1.

Output. Return the number of connected components among all declared vertices.

Rules. Vertices belong together if an undirected path connects them, directly or through other vertices. Every isolated vertex forms its own component. Repeated edges and self-loops do not merge additional components. Preserve the inputs. Zero vertices returns zero.

Example. Five vertices and edges [[0, 1], [1, 2], [3, 4]] return 2. The components are {0, 1, 2} and {3, 4}; six vertices without edges return 6.

Picture

With six nodes and edges 0-1, 0-2, 3-4, the groups are {0,1,2}, {3,4}, and {5}.

New startAfter its floodLater starts skipped
0seen={0,1,2}, components=11 and 2
3seen={0,1,2,3,4}, components=24
5seen={0,1,2,3,4,5}, components=3None

Node five still launches a flood. Its stack empties immediately because it has no neighbors.

This is permanent component coverage with explicit vertices instead of grid cells. An unseen start cannot belong to a completed flood: that flood would have reached it. Each launch therefore counts one new component, and its full coverage prevents double counting.

Mark a vertex before pushing it. seen means discovered, not fully expanded; a pending vertex must not be scheduled again. The LIFO stack expands the first group in order 0,2,1.

Duplicate edges and self-loops do not change these groups, but they still require scans. Do not use this undirected flood to count directed strongly connected components.

Problem trace

Separate union-find comparison: a duplicate union cannot remove a group

Worked example: only a successful union reduces the component countFour nodes begin as four components. Joining (0,1) and (2,3) leaves two; joining (1,0) again does not reduce that count.An already-connected pair does notremove another componentAfter two earlier successful unions01232 componentsTest 1-0: already in one group01232 components: count unchangedThe duplicate 1-0 union leaves bothexisting groups intact.
Read it this way: Four nodes begin as four components. Joining (0,1) and (2,3) leaves two; joining (1,0) again does not reduce that count. Which actual group would disappear if the duplicate union incorrectly decremented two to one?
Reference drawing

Problem trace

Count new traversals, not every node reached within them

Worked example: only a successful union reduces the component countFour nodes begin as four components. Joining (0,1) and (2,3) leaves two; joining (1,0) again does not reduce that count.An already-connected pair does notremove another componentAfter two earlier successful unions01232 componentsTest 1-0: already in one group01232 components: count unchangedThe duplicate 1-0 union leaves bothexisting groups intact.
Execution trace
Input and goalCount separate groups in an undirected graph.
Build the graph and initializeBuild both directions for edges 0-1, 0-2 and 3-4. Node five has no neighbors. Start with seen={}, components=0.
012345
seen{}
Original undirected adjacency lists
012
10
20
34
43
5none
stack: top at rightempty
edgeTopology0-1, 0-2, 3-4; node 5 isolatedrowMeaningrow index = node; cells = adjacent nodesadjacency0:[1,2]; 1:[0]; 2:[0]; 3:[4]; 4:[3]; 5:[]seenState{}components0
queue
[]
edge topology
0-1, 0-2, 3-4; node 5 isolated
row meaning
row index = node; cells = adjacent nodes

Recognize it
Use it when an undirected graph may contain multiple disconnected groups, including isolated vertices, and the task asks how many maximal reachable groups exist.
Keep true
After processing outer-loop starts below the current index, every vertex in their components is seen and components equals the number of DFS launches. A seen vertex can never launch another count.
Reuse it
A global visited set partitions a graph: every new search root contributes one component and consumes all vertices that must not contribute again. This transfers to islands, provinces, and cluster counting.
Build both directions for edges 0-1, 0-2 and 3-4. Node five has no neighbors. Start with seen={}, components=0. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does visiting nodes 1 and 2 not add components, while visiting isolated node 5 does?
Read it this way: Four nodes begin as four components. Joining (0,1) and (2,3) leaves two; joining (1,0) again does not reduce that count. Which actual group would disappear if the duplicate union incorrectly decremented two to one?

Code

def count_components(node_count: int, edges: list[list[int]]) -> int:
   graph = [[] for _ in range(node_count)]
   for first, second in edges:
      graph[first].append(second)
      graph[second].append(first)

   seen: set[int] = set()
   components = 0
   for start in range(node_count):
      if start in seen:
         continue

      components += 1
      seen.add(start)
      stack = [start]
      while stack:
         for neighbor in graph[stack.pop()]:
            if neighbor not in seen:
               seen.add(neighbor)
               stack.append(neighbor)
   return components

Expected work is . Total storage is for adjacency plus for seen and the stack.

Change the Component Summary

Start from count_components. Keep the same permanent marks and change what each completed flood contributes.

  1. Return group sizes.

    New task: Return the cardinality of each component.

    Picture and change: Count one vertex per pop. Append the size only when that component’s stack empties.

    Code: Complete replacement:

    def component_sizes(node_count, edges):
       graph = [[] for _ in range(node_count)]
       for first, second in edges:
          graph[first].append(second)
          graph[second].append(first)
       seen, sizes = set(), []
       for start in range(node_count):
          if start in seen:
             continue
          seen.add(start)
          stack, size = [start], 0
          while stack:
             node = stack.pop()
             size += 1
             for neighbor in graph[node]:
                if neighbor not in seen:
                   seen.add(neighbor)
                   stack.append(neighbor)
          sizes.append(size)
       return sorted(sizes)

    Check: The example gives [1,2,3], whose sum is six. With four isolated vertices, return [1,1,1,1].

    Use when: Group-size distribution matters. Sorting stabilizes output, not connectivity. For components it adds work to the flood.

  2. Count unreachable unordered pairs.

    New task: Count vertex pairs lying in different components, without listing every pair.

    Picture and change: Remove a whole group’s size from remaining, then pair that group with every still-unprocessed vertex. No vertex within the same component contributes. Every cross-component pair contributes when its earlier group is processed.

    Code: Uses component_sizes above:

    def unreachable_pairs(node_count, edges):
       remaining, pairs = node_count, 0
       for size in component_sizes(node_count, edges):
          remaining -= size
          pairs += size * remaining
       return pairs

    Check: Sorted sizes [1,2,3] give . Four isolated vertices give six pairs.

    Use when: Connectivity supplies a combinatorial summary. This version inherits the helper’s sorting cost and total storage.

Rebuild Coverage

Why is seen not restored after each component flood?

Answer: A reached vertex permanently belongs to that counted component. Unlike Word Search, marks are not temporary path exclusions.