Remove a character from a string to make it a palindrome | Utility method to check if substring from low to high is palindrome or not . ; This method returns - 1 if it is not possible to make string a palindrome . It returns - 2 if string is already a palindrome . Otherwise it returns index of character whose removal can make the whole string palindrome . ; Initialize low and right by both the ends of the string ; loop until low and high cross each other ; If both characters are equal then move both pointer towards end ; * If removing str [ low ] makes the * whole string palindrome . We basically * check if substring str [ low + 1. . high ] * is palindrome or not . ; * If removing str [ high ] makes the whole string * palindrome . We basically check if substring * str [ low + 1. . high ] is palindrome or not . ; We reach here when complete string will be palindrome if complete string is palindrome then return mid character ; Driver Code
function isPalindrome ( str , low , high ) { while ( low < high ) { if ( str . charAt ( low ) != str . charAt ( high ) ) return false ; low ++ ; high -- ; } return true ; } function possiblePalinByRemovingOneChar ( str ) { var low = 0 , high = str . length - 1 ; while ( low < high ) { if ( str . charAt ( low ) == str . charAt ( high ) ) { low ++ ; high -- ; } else { if ( isPalindrome ( str , low + 1 , high ) ) return low ; if ( isPalindrome ( str , low , high - 1 ) ) return high ; return - 1 ; } } return - 2 ; } var str = " " ; var idx = possiblePalinByRemovingOneChar ( str ) ; if ( idx == - 1 ) document . write ( " " ) ; else if ( idx == - 2 ) document . write ( " " + " " ) ; else document . write ( " " + " " + idx ) ;