Minimum size substring to be removed to make a given string palindromic | Function to find palindromic prefix of maximum length ; Finding palindromic prefix of maximum length ; Checking if curr subString is palindrome or not . ; Condition to check if the prefix is a palindrome ; If no palindrome exist ; Function to find the maximum size palindrome such that after removing minimum size subString ; Finding prefix and suffix of same length ; Matching the ranges ; Case 1 : Length is even and whole String is palindrome ; Case 2 : Length is odd and whole String is palindrome ; Adding that mid character ; Add prefix or suffix of the remaining String or suffix , whichever is longer ; Reverse the remaining String to find the palindromic suffix ; Driver Code
function palindromePrefix ( S ) { let n = S . length ; for ( let i = n - 1 ; i >= 0 ; i -- ) { let curr = S . substr ( 0 , i + 1 ) ; let l = 0 , r = curr . length - 1 ; let is_palindrome = true ; while ( l < r ) { if ( curr [ l ] != curr [ r ] ) { is_palindrome = false ; break ; } l ++ ; r -- ; } if ( is_palindrome ) return curr ; } return " " ; } function maxPalindrome ( S ) { let n = S . length ; if ( n <= 1 ) { return S ; } let pre = " " , suff = " " ; let i = 0 , j = n - 1 ; while ( S [ i ] == S [ j ] && i < j ) { i ++ ; j -- ; } i -- ; j ++ ; pre = S . substr ( 0 , i + 1 ) ; suff = S . substr ( j ) ; if ( j - i == 1 ) { return pre + suff ; } if ( j - i == 2 ) { let mid_char = S . substr ( i + 1 , i + 2 ) ; return pre + mid_char + suff ; } let rem_str = S . substr ( i + 1 , j ) ; let pre_of_rem_str = palindromePrefix ( rem_str ) ; rem_str = reverse ( rem_str ) ; let suff_of_rem_str = palindromePrefix ( rem_str ) ; if ( pre_of_rem_str . length >= suff_of_rem_str . length ) { return pre + pre_of_rem_str + suff ; } else { return pre + suff_of_rem_str + suff ; } } function reverse ( input ) { let a = input . split ( ' ' ) ; let l , r = a . length - 1 ; for ( l = 0 ; l < r ; l ++ , r -- ) { let temp = a [ l ] ; a [ l ] = a [ r ] ; a [ r ] = temp ; } return parseInt ( a ) ; } let S = " " ; document . write ( maxPalindrome ( S ) ) ;