Pairs of strings which on concatenating contains each character of " string " | Python3 implementation of the 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
MAX = 64 NEW_LINE def getBitmask ( s ) : NEW_LINE INDENT temp = 0 NEW_LINE for j in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ j ] == ' s ' ) : NEW_LINE INDENT temp = temp | 1 NEW_LINE DEDENT elif ( s [ j ] == ' t ' ) : NEW_LINE INDENT temp = temp | 2 NEW_LINE DEDENT elif ( s [ j ] == ' r ' ) : NEW_LINE INDENT temp = temp | 4 NEW_LINE DEDENT elif ( s [ j ] == ' i ' ) : NEW_LINE INDENT temp = temp | 8 NEW_LINE DEDENT elif ( s [ j ] == ' n ' ) : NEW_LINE INDENT temp = temp | 16 NEW_LINE DEDENT elif ( s [ j ] == ' g ' ) : NEW_LINE INDENT temp = temp | 32 NEW_LINE DEDENT DEDENT return temp NEW_LINE DEDENT def countPairs ( arr , n ) : NEW_LINE INDENT bitMask = [ 0 for i in range ( MAX ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT bitMask [ getBitmask ( arr [ i ] ) ] += 1 NEW_LINE DEDENT cnt = 0 NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT for j in range ( i , MAX ) : NEW_LINE INDENT if ( ( i j ) == ( MAX - 1 ) ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT cnt += ( ( bitMask [ i ] * bitMask [ i ] - 1 ) // 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT cnt += ( bitMask [ i ] * bitMask [ j ] ) NEW_LINE DEDENT DEDENT DEDENT DEDENT return cnt NEW_LINE DEDENT arr = [ " strrr " , " string " , " gstrin " ] NEW_LINE n = len ( arr ) NEW_LINE print ( countPairs ( arr , n ) ) NEW_LINE