AlgoFrames

Spot the bug: union without roots

Standard · Find the bug · about 8 min

This function should count the connected components of an undirected graph, but it is wrong for some inputs. Click the line with the bug, then fix it.

Example 1

Input:

[4,[[0,1],[0,2],[1,2]]]

Output:

2

The buggy code returns 1 here.

Constraints

  • 1 ≤ n ≤ 2000
  • 0 ≤ edges.length ≤ 2000

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