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
def prefix ( string ) : NEW_LINE INDENT k = 1 ; NEW_LINE n = len ( string ) ; NEW_LINE g = [ ] ; NEW_LINE flag = 0 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( string [ i ] == string [ 0 ] ) : NEW_LINE INDENT g . append ( i ) ; NEW_LINE flag = 1 ; NEW_LINE DEDENT DEDENT if ( flag == 0 ) : NEW_LINE INDENT print ( string ) ; NEW_LINE DEDENT else : NEW_LINE INDENT length = len ( g ) ; NEW_LINE while ( k < g [ 0 ] ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE for j in range ( length ) : NEW_LINE INDENT if ( string [ g [ j ] + k ] == string [ k ] ) : NEW_LINE INDENT cnt += 1 ; NEW_LINE DEDENT DEDENT if ( cnt == len ) : NEW_LINE INDENT k += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT for i in range ( k + 1 ) : NEW_LINE INDENT print ( string [ i ] , end = " " ) ; NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " abcab " ; NEW_LINE prefix ( string ) ; NEW_LINE DEDENT