mix the colors

This problem was part of the March 18 Contest and is a fairly easy one, specially with Python it becomes super easy when it comes to problems like these as the main core code implementation is being abstracted away and only the concept and the idea is left behind, well, I took this problem in the Morning, for I had thought of thinking about an idea for this during the classes which don't have even a Semblance of Seriousness( except a few ones ) so that I don't feel like the whole class was a waste, at least I would do something worth that much time instead of just listening to those blurting fools. I had made my own assumptions about the problem and considered even those cases which were not required, but it was easier than expected.




Code Implementation:-
from collections import Counter as ct
# print("Hola Todo El Mundo!")
for _ in range(int(input())):
    n=int(input())
    colors=list(map(int,input().split()))
    colors=dict(ct(colors))
    # print(colors)
    ans=0
    for freq in colors.values():
        if(freq!=1):
            ans+=(freq-1)
    print(ans)

Explanation:-
This Problem just boils down to a single simple idea, and it's that if we will observe the main operation and it's nature that we are performing then we would get to know that we are just taking two numbers and increasing one of them( which number? doesn't matter, only we should see that 1 number is increased of the 2 and it is increased by the 2nd num). So, eventually we have the sole motive to make all the pairs distinct Now here, it's not specified that the pairs are consecutive, so they are not! Which means the pairs can be any numbers(colors) of the array and we just have to make all of them distinct bcz pairs can be any 2 numbers. So, the minimum no. of operations to make all the numbers distinct, suppose we have the frequency of a number as 4, so we would just change the 3 occurrences of that number and we don't have to change the last occurrence bcz obviously the last occurrence will be distinct, thus satisfying the end result. So, by using the Counter function of Collections module we get the frequencies and we just take -1 of those which are not 1( means they are greater than 1).

Comments

Popular Posts