Pairs of strings which on concatenating contains each character of " string " | JavaScript implementation of the above approach ; Function to return the bitmask for the string ; Function to return the count of pairs ; bitMask [ i ] will store the count of strings from the array whose bitmask is i ; To store the count of pairs ; MAX - 1 = 63 i . e . 111111 in binary ; arr [ i ] cannot make s pair with itself i . e . ( arr [ i ] , arr [ i ] ) ; Driver code
const MAX = 64 ; function getBitmask ( s ) { var temp = 0 ; for ( var j = 0 ; j < s . length ; j ++ ) { switch ( s [ j ] ) { case " " : temp = temp | 1 ; break ; case " " : temp = temp | 2 ; break ; case " " : temp = temp | 4 ; break ; case " " : temp = temp | 8 ; break ; case " " : temp = temp | 16 ; break ; case " " : temp = temp | 32 ; break ; default : break ; } } return temp ; } function countPairs ( arr , n ) { var bitMask = new Array ( MAX ) . fill ( 0 ) ; for ( var i = 0 ; i < n ; i ++ ) bitMask [ getBitmask ( arr [ i ] . split ( " " ) ) ] ++ ; var cnt = 0 ; for ( var i = 0 ; i < MAX ; i ++ ) { for ( var j = i ; j < MAX ; j ++ ) { if ( ( i j ) === MAX - 1 ) { if ( i === j ) cnt += parseInt ( ( bitMask [ i ] * bitMask [ i ] - 1 ) / 2 ) ; else cnt += bitMask [ i ] * bitMask [ j ] ; } } } return cnt ; } var arr = [ " " , " " , " " ] ; var n = arr . length ; document . write ( countPairs ( arr , n ) ) ;