Return connected component sizes in an undirected graph
A community platform wants to spot isolated friend circles. Users are nodes, and every “follows” relationship links two users. A cluster is a group of users that can reach each other through links, in either direction. The moderation dashboard shows how many clusters exist and how big each one is.
Implement clusterSizes(nodes, links). It returns the size of every cluster, sorted from largest to smallest. The number of clusters is the length of the result.
clusterSizes(nodes, links) // => number[]
nodes is an array of node ids. Ids are strings or numbers, and '7' and 7 are different nodes. The array may contain duplicates; count each id once.links is an array of [a, b] pairs. Links are undirected: ['ann', 'bo'] connects both ways.nodes still exists.['ann', 'ann']) are allowed and change nothing beyond making the node exist.clusterSizes(
['ann', 'bo', 'cy', 'dee', 'eli', 'fay'],
[['ann', 'bo'], ['cy', 'bo'], ['dee', 'eli']],
);
// => [3, 2, 1] (ann-bo-cy, dee-eli, fay alone)
clusterSizes(['x'], [['y', 'z'], ['z', 'y'], ['x', 'x']]);
// => [2, 1] (y and z exist because of the links)
clusterSizes([1, '1', 2], [[1, 2]]);
// => [2, 1]
clusterSizes([], []);
// => []