Codevita Online Communities-Even Groups

Can anyone give me hint on how to solve this question?

1 Like

You can easily solve it using Disjoint-Set Data structure(using Union and Find procedures) . Its pretty straight forward . Remember to keep track of the number of nodes in each set . (Which is not that difficult !) .
For more reference : Hope this helps !


As already answered, this problems screams for a union-find data structure.
Another alternative when working with connected parts of a graph is to employ DFS.
When doing DFS, you already use an array for bookkeeping which vertex has already been visited.
In one run you will visit exactly the vertices in one component (counting during DFS will yield part of the result for the question).
Now start DFS not once but for each vertex that has not yet been visited (iterate over the array).
This yields the count for every component.