text: Length of longest common prefix possible by rearranging strings in a given array | 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: function longComPre ( arr , N ) { let freq = new Array ( N ) ; for ( let i = 0 ; i < N ; i ++ ) { freq [ i ] = new Array ( 256 ) ; for ( let j = 0 ; j < 256 ; j ++ ) { freq [ i ] [ j ] = 0 ; } } for ( let i = 0 ; i < N ; i ++ ) { let M = arr [ i ] . length ; for ( let j = 0 ; j < M ; j ++ ) { freq [ i ] [ arr [ i ] [ j ] . charCodeAt ( 0 ) ] ++ ; } } let maxLen = 0 ; for ( let j = 0 ; j < 256 ; j ++ ) { let minRowVal = Number . MAX_VALUE ; for ( let i = 0 ; i < N ; i ++ ) { minRowVal = Math . min ( minRowVal , freq [ i ] [ j ] ) ; } maxLen += minRowVal ; } return maxLen ; } let arr = [ " " , " " , " " ] ; let N = 3 ; document . write ( longComPre ( arr , N ) ) ;