Store the frequency of respective counts of set bits
setbits = dict ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if bitscount [ arr [ i ] ] in setbits : NEW_LINE INDENT setbits [ bitscount [ arr [ i ] ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT setbits [ bitscount [ arr [ i ] ] ] = 1 NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for it in setbits . values ( ) : NEW_LINE INDENT ans += it * ( it - 1 ) // 2 NEW_LINE DEDENT return ans NEW_LINE