#81 · Graphs · Intermediate · 70 XP · about 12 min
There are n people, numbered 0 to n - 1, and a list of friendships pairs, where [a, b] means a and b are friends. Friends of friends end up in the same group: if Ana is friends with Ben and Ben is friends with Cy, all three are in one group, even if Ana and Cy have never met. Write count_groups(n, pairs) that returns the number of groups.
A person with no friends forms a group of one.
count_groups(5, [[0, 1], [1, 2], [3, 4]]) # returns 2 count_groups(4, []) # returns 4 count_groups(3, [[0, 1], [1, 2], [2, 0]]) # returns 1
In the first example people 0, 1 and 2 form one group and people 3 and 4 form another.
0 <= n <= 2000, with up to 5,000 pairs.Ready?
Accept the challenge to start writing. A small timer counts the time this page is in view.
Output appears here.