Skip to contentKEEP THE CRAFTTHE SANCTUARY

Count Components with Union-Find

Count the connected components of an undirected graph with the union-find template.

The problem

Implement component_count(node_count, edges). The nodes are labeled 0 to node_count - 1, and each edge [a, b] connects a and b in both directions. Return the number of connected components, that is, how many separate pieces the graph falls into. For example, with 5 nodes and edges [[0, 1], [1, 2], [3, 4]] there are 2 components: {0, 1, 2} and {3, 4}. 1 <= node_count <= 2000, there are at most 5000 edges, no edge appears twice, and edges may be empty.

Starter code

def component_count(node_count, edges):
    pass

Public examples

  1. node_count = 5, edges = [[0, 1], [1, 2], [3, 4]]gives2
  2. node_count = 3, edges = [[0, 1], [1, 2], [0, 2]]gives1
  3. node_count = 4, edges = [[0, 1], [2, 3], [1, 3], [0, 2]]gives1

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.