Find index i such that prefix of S1 and suffix of S2 till i form a palindrome when concatenated | Java implementation of the above approach ; 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
class GFG { static boolean isPalindrome ( String s , int i , int j ) { while ( i < j ) { if ( s . charAt ( i ) != s . charAt ( j ) ) return false ; i ++ ; j -- ; } return true ; } static int getIndex ( String s1 , String s2 , int len ) { int i = 0 , j = len - 1 ; while ( i < j ) { if ( s1 . charAt ( i ) != s2 . charAt ( j ) ) { break ; } i ++ ; j -- ; } if ( i == j ) { return i - 1 ; } else if ( isPalindrome ( s2 , i , j ) ) return i - 1 ; else if ( isPalindrome ( s1 , i , j ) ) return j ; return - 1 ; } public static void main ( String args [ ] ) { String s1 = " abcdf " , s2 = " sfgba " ; int len = s1 . length ( ) ; System . out . println ( getIndex ( s1 , s2 , len ) ) ; } }