Count Connected Groups
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
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] → 3In 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
firstandsecondis between0andn − 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.
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.
Expected is the reference solution's answer, from the judge. An input that breaks the statement's other rules may get any answer.