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
function isPalindrome ( s , i , j ) { while ( i < j ) { if ( s [ i ] != s [ j ] ) return false ; i ++ ; j -- ; } return true ; } function getIndex ( s1 , s2 , len ) { let i = 0 , j = len - 1 ; while ( i < j ) { if ( s1 [ i ] != s2 [ 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 ; } let s1 = " " , s2 = " " ; let len = s1 . length ; document . write ( getIndex ( s1 , s2 , len ) + " " ) ;