text: Length of longest common prefix possible by rearranging strings in a given array | Java 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 String 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 java . util . * ; class GFG { static int longComPre ( String arr [ ] , int N ) { int [ ] [ ] freq = new int [ N ] [ 256 ] ; for ( int i = 0 ; i < N ; i ++ ) { int M = arr [ i ] . length ( ) ; for ( int j = 0 ; j < M ; j ++ ) { freq [ i ] [ arr [ i ] . charAt ( j ) ] ++ ; } } int maxLen = 0 ; for ( int j = 0 ; j < 256 ; j ++ ) { int minRowVal = Integer . MAX_VALUE ; for ( int i = 0 ; i < N ; i ++ ) { minRowVal = Math . min ( minRowVal , freq [ i ] [ j ] ) ; } maxLen += minRowVal ; } return maxLen ; } public static void main ( String [ ] args ) { String arr [ ] = { " aabdc " , " abcd " , " aacd " } ; int N = 3 ; System . out . print ( longComPre ( arr , N ) ) ; } }