Connected Components

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code

Write countComponents(n, edges). An undirected graph has n nodes numbered 0 to n − 1, and each pair [a, b] in edges joins two different nodes; a pair may appear more than once. Return the number of connected components: groups of nodes linked to each other through edges, where a node with no edges is a group of its own. For example, countComponents(5, [[0, 1], [1, 2], [3, 4]]) is 2. The checks include graphs with 100,000 nodes and 100,000 edges, one of them a single path through every node, which is too long for recursion. A union-find needs path compression or union by size to be fast enough.

Your code must pass

  • Counts the groups in a small graph
  • Counts a node with no edges as its own group
  • Merges groups that a later edge joins
  • Is fast enough for 100,000 nodes and edges