Back to Practice
#0242

Count Connected Components with Union-Find

MediumDSA28 min20 XP

Problem

Given n nodes labeled 0 to n-1 and undirected edges, return the number of connected components.

Why This Matters

Union-find is the fastest mental model for dynamic connectivity questions where edges merge groups.

Function Signature

def count_components(n, edges):

Examples

Example 1
Inputn = 5, edges = [[0, 1], [1, 2], [3, 4]]
Output2

Nodes 0-1-2 form one component and 3-4 form another.

Constraints

  • Return the exact requested value.
  • Handle empty or small inputs when the prompt allows them.
  • Prefer the target DSA pattern over brute force when the input can grow.
CodePython
Visible browser tests run here when available.
Testcases2 visible / 3 hidden categories
Two components
Inputn = 5, edges = [[0, 1], [1, 2], [3, 4]]
Expected2

Three unions reduce five nodes to two components.

Duplicate edge
Inputn = 3, edges = [[0, 1], [1, 0]]
Expected2

The second edge does not reduce the count again.

Hidden Test Categories
no edgesfully connected graphself-loop edge