text: Length of longest common prefix possible by rearranging strings in a given array | Python3 program to implement the above approach ; Function to get the length of the longest common prefix by rearranging the strings ; freq [ i ] [ j ] : stores the frequency of a character ( = j ) in a arr [ i ] ; Traverse the given array ; Stores length of current string ; Traverse current string of the given array ; Update the value of freq [ i ] [ arr [ i ] [ j ] ] ; Stores the length of longest common prefix ; Count the minimum frequency of each character in in all the strings of arr [ ] ; Stores minimum value in each row of freq [ ] [ ] ; Calculate minimum frequency of current character in all the strings . ; Update minRowVal ; Update maxLen ; Driver Code
code: import sys NEW_LINE def longComPre ( arr , N ) : NEW_LINE INDENT freq = [ [ 0 for i in range ( 256 ) ] for i in range ( N ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT M = len ( arr [ i ] ) NEW_LINE for j in range ( M ) : NEW_LINE INDENT freq [ i ] [ ord ( arr [ i ] [ j ] ) ] += 1 NEW_LINE DEDENT DEDENT maxLen = 0 NEW_LINE for j in range ( 256 ) : NEW_LINE INDENT minRowVal = sys . maxsize NEW_LINE for i in range ( N ) : NEW_LINE INDENT minRowVal = min ( minRowVal , freq [ i ] [ j ] ) NEW_LINE DEDENT maxLen += minRowVal NEW_LINE DEDENT return maxLen NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ " aabdc " , " abcd " , " aacd " ] NEW_LINE N = 3 NEW_LINE print ( longComPre ( arr , N ) ) NEW_LINE DEDENT