Store the frequency of respective counts of set bits
Dictionary < int , int > setbits = new Dictionary < int , int > ( ) ; for ( int j = 0 ; j < N ; j ++ ) { if ( setbits . ContainsKey ( bitscount [ arr [ j ] ] ) ) { setbits [ bitscount [ arr [ j ] ] ] ++ ; } else { setbits [ bitscount [ arr [ j ] ] ] = 1 ; } } int ans = 0 ; foreach ( KeyValuePair < int , int > it in setbits ) { ans += it . Value * ( it . Value - 1 ) / 2 ; } return ans ; }