Pairs of strings which on concatenating contains each character of " string " | Java 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
class GFG { static int MAX = 64 ; static int getBitmask ( char [ ] s ) { int temp = 0 ; for ( int j = 0 ; j < s . length ; j ++ ) { switch ( s [ j ] ) { case ' s ' : temp = temp | ( 1 ) ; break ; case ' t ' : temp = temp | ( 2 ) ; break ; case ' r ' : temp = temp | ( 4 ) ; break ; case ' i ' : temp = temp | ( 8 ) ; break ; case ' n ' : temp = temp | ( 16 ) ; break ; case ' g ' : temp = temp | ( 32 ) ; break ; default : break ; } } return temp ; } static int countPairs ( String arr [ ] , int n ) { int [ ] bitMask = new int [ MAX ] ; for ( int i = 0 ; i < n ; i ++ ) bitMask [ getBitmask ( arr [ i ] . toCharArray ( ) ) ] ++ ; int cnt = 0 ; for ( int i = 0 ; i < MAX ; i ++ ) { for ( int j = i ; j < MAX ; j ++ ) { if ( ( i j ) == ( MAX - 1 ) ) { if ( i == j ) cnt += ( ( bitMask [ i ] * bitMask [ i ] - 1 ) / 2 ) ; else cnt += ( bitMask [ i ] * bitMask [ j ] ) ; } } } return cnt ; } public static void main ( String [ ] args ) { String arr [ ] = { " strrr " , " string " , " gstrin " } ; int n = arr . length ; System . out . println ( countPairs ( arr , n ) ) ; } }