Count Connected Groups

EasyGraphs≈ 25 min

There are n people, numbered from 0 to n − 1. The friendships between them are given as two lists of the same length, first and second: person first[i] and person second[i] are friends, both ways.

Two people are in the same group when they are friends, or are linked through a chain of friends: a friend of a friend, and so on. Return the number of groups. A person with no friends is a group of their own.

Examples

text
n = 5, first = [0, 1, 3], second = [1, 2, 4]          →  2
n = 4, first = [], second = []                        →  4
n = 3, first = [0, 1], second = [1, 2]                →  1
n = 6, first = [0, 2, 4, 1], second = [1, 3, 5, 0]    →  3

In the first example 0, 1 and 2 form one group through the friendships 0–1 and 1–2, and 3, 4 another.

Constraints

  • Between 1 and 10,000 people and up to 20,000 friendships; every number in first and second is between 0 and n − 1.
  • The same friendship may be listed twice, and a person may be listed as their own friend.
  • Aim for O(n + m), n people and m friendships: each person and each friendship looked at a constant number of times.
Sound off. Turn on for key clicks and a chime when the tests pass.Inline suggestions off. Recommended while you are learning. Turn on to complete words as you type.
Console
›Run to see what your code prints

Run checks the 4 visible cases here, in your browser. Submit runs all 8 on the judge, 4 of them hidden, and measures how your solution scales.