Store the frequency of respective counts of set bits
Map < Integer , Integer > setbits = new HashMap < > ( ) ; for ( int j = 0 ; j < N ; j ++ ) { setbits . put ( bitscount [ arr [ j ] ] , setbits . getOrDefault ( bitscount [ arr [ j ] ] , 0 ) + 1 ) ; } int ans = 0 ; for ( int it : setbits . values ( ) ) { ans += it * ( it - 1 ) / 2 ; } return ans ; }