I read the editorial and have been trying it,but i cant figure out what is wrong with my code.
I used dfs to check the connectivity of the graph.Also took care of the case 0f all the numbers being 47.
Here is a link to my code.

Your code fails for the following test cases



41 47 47 47


41 41 41 41 41 43

Your code prints :


47 47 47 47


47 41 41 41 41 43

The answer will be 0 and the array itself in both the cases.
The reason is, you are checking the connectedness of the graph at “all values from 2 to 51”. This should not be done as in both the above cases you will get comp as 2 and 2 respectively. Instead, try to check the connectedness at all the “indices” of the array and not on the values, if any index is not connected and is not 41 change it to 47 else change it to 41.

Thanks man for pointing it out bugs like these are hard to catch.
I think i’ll just hash the frequency of each element and increment comp accordingly.