Use KMP algorithm
while ( i < n ) : NEW_LINE INDENT if ( C [ i ] == C [ ll ] ) : NEW_LINE INDENT ll += 1 NEW_LINE longestPalindrome [ i ] = ll NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( ll != 0 ) : NEW_LINE INDENT ll = longestPalindrome [ ll - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT longestPalindrome [ i ] = 0 NEW_LINE i += 1 NEW_LINE DEDENT DEDENT DEDENT ans = C [ 0 : longestPalindrome [ n - 1 ] ] NEW_LINE return ans NEW_LINE