Skip to content
DeepForgeby svx
All problems
EasyAlgorithmsal-084

Connected Components

Problem

Given n nodes labelled 0 to n-1 and undirected edges as [u, v] pairs, return the number of connected components including isolated nodes.

Use union-find to merge the endpoints of every edge, then count the distinct roots. Return 0 when n is 0.

Hint

Nodes with no edges are each their own component.

Test cases

case 1
in: [5,[[0,1],[1,2],[3,4]]]
expected: 2
case 2
in: [5,[]]
expected: 5
case 3
in: [1,[]]
expected: 1
case 4
in: [0,[]]
expected: 0
case 5
in: [4,[[0,1],[1,2],[2,3]]]
expected: 1
Starter codePython
def count_components(n, edges):
    # Your code here
    pass

5 test cases · run your code against them in the editor