AlgoFrames

Number of components

Standard · Write code · about 12 min

An undirected graph has n nodes numbered 0 to n - 1 and a list of edges. Return the number of connected components.

Use union-find: start with n sets and merge the two ends of every edge.

Example 1

Input:

[5,[[0,1],[1,2],[3,4]]]

Output:

2

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

Example 2

Input:

[5,[[0,1],[1,2],[2,3],[3,4]]]

Output:

1

Constraints

  • 1 ≤ n ≤ 2000
  • 0 ≤ edges.length ≤ 2000
  • 0 ≤ a, b < n; an edge may repeat or join a node to itself

Learn the idea first: Disjoint set union: find, union, rank, path compression, a visual lesson.

More Disjoint set union: find, union, rank, path compression problems