Longest prefix in a string with highest frequency | Function to find Longest prefix string with the highest frequency ; storing all indices where first element is found ; if the first letter in the string does not occur again then answer will be the whole string ; loop till second appearance of the first element ; check one letter after every stored index ; If there is no mismatch we move forward ; otherwise we stop ; Driver Code
function prefix ( str ) { let k = 1 , j ; let n = str . length ; let g = [ ] ; let flag = 0 ; for ( let i = 1 ; i < n ; i ++ ) { if ( str [ i ] == str [ 0 ] ) { g . push ( i ) ; flag = 1 ; } } if ( flag == 0 ) { document . write ( ( str . join ( " " ) ) ) ; } else { let len = g . length ; while ( k < g [ 0 ] ) { let cnt = 0 ; for ( j = 0 ; j < len ; j ++ ) { if ( ( g [ j ] + k ) < n && str [ g [ j ] + k ] == str [ k ] ) { cnt ++ ; } } if ( cnt == len ) { k ++ ; } else { break ; } } for ( let i = 0 ; i < k ; i ++ ) { document . write ( str [ i ] ) ; } document . write ( " " ) ; } } let str = " " ; prefix ( str ) ;