Find index i such that prefix of S1 and suffix of S2 till i form a palindrome when concatenated | Function that returns true if the sub - string starting from index i and ending at index j is a palindrome ; Function to get the required index ; Start comparing the two strings from both ends . ; Break from the loop at first mismatch ; If it is possible to concatenate the strings to form palindrome , return index ; If remaining part for s2 is palindrome ; If remaining part for s1 is palindrome ; If not possible , return - 1 ; Driver Code
def isPalindrome ( s , i , j ) : NEW_LINE INDENT while ( i < j ) : NEW_LINE INDENT if ( s [ i ] != s [ j ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT i += 1 ; NEW_LINE j -= 1 ; NEW_LINE DEDENT return True ; NEW_LINE DEDENT def getIndex ( s1 , s2 , length ) : NEW_LINE INDENT i = 0 ; j = length - 1 ; NEW_LINE while ( i < j ) : NEW_LINE INDENT if ( s1 [ i ] != s2 [ j ] ) : NEW_LINE INDENT break ; NEW_LINE DEDENT i += 1 ; NEW_LINE j -= 1 ; NEW_LINE DEDENT if ( i == j ) : NEW_LINE INDENT return i - 1 ; NEW_LINE DEDENT elif ( isPalindrome ( s2 , i , j ) ) : NEW_LINE INDENT return i - 1 ; NEW_LINE DEDENT elif ( isPalindrome ( s1 , i , j ) ) : NEW_LINE INDENT return j ; NEW_LINE DEDENT return - 1 ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s1 = " abcdf " ; NEW_LINE s2 = " sfgba " ; NEW_LINE length = len ( s1 ) ; NEW_LINE print ( getIndex ( s1 , s2 , length ) ) ; NEW_LINE DEDENT