FunctionRacerProblemsRace

Cable Groups

EasyGraphsPython, JavaScript, TypeScript, Java, C++

There are n computers numbered 0 to n - 1. cables lists direct connections as pairs [a, b]: a cable joins computer a and computer b, and data can flow along it in both directions.

Two computers belong to the same group when data can travel between them through one or more cables. Return the number of groups. A computer with no cables forms a group by itself, so with no cables at all the answer is n. The same pair may appear more than once; repeats change nothing.

Example 1

n 5
cables [[0,1],[1,2],[3,4]]
returns 2

Computers 0, 1 and 2 are linked through two cables, computers 3 and 4 through one, so there are 2 groups.

Example 2

n 4
cables [[0,1]]
returns 3

Computers 0 and 1 form one group; computers 2 and 3 are each alone, giving 3 groups.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Graphs problems