Remove a character from a string to make it a palindrome

Given a string, we need to check whether it is possible to make this string a palindrome after removing exactly one character from this.

Examples:

Input  : str = “abcba”
Output : Yes
we can remove character ‘c’ to make string palindrome

Input  : str = “abcbea”
Output : Yes
we can remove character ‘e’ to make string palindrome

Input : str = “abecbea”
It is not possible to make this string palindrome 
just by removing one character 



We can solve this problem by finding the position of mismatch. We start looping in the string by keeping two pointers at both the ends which traverse towards mid position after each iteration, this iteration will stop when we find a mismatch, as it is allowed to remove just one character we have two choices here,

At mismatch, either remove character pointed by left pointer or remove character pointed by right pointer.

We will check both the cases, remember as we have traversed equal number of steps from both sides, this mid string should also be a palindrome after removing one character, so we check two substrings, one by removing left character and one by removing right character and if one of them is palindrome then we can make complete string palindrome by removing corresponding character, and if both substrings are not palindrome then it is not possible to make complete string a palindrome under given constraint.

C/C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C/C++ program to check whether it is possible to make
// string palindrome by removing one character
#include <bits/stdc++.h>
using namespace std;
  
// Utility method to check if substring from low to high is
// palindrome or not.
bool isPalindrome(string::iterator low, string::iterator high)
{
    while (low < high)
    {
       if (*low != *high)
          return false;
       low++;
       high--;
    }
    return true;
}
  
// 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.
int possiblePalinByRemovingOneChar(string str)
{
    //  Initialize low and right by both the ends of the string
    int low = 0, high = str.length() - 1;
  
    //  loop untill low and high cross each other
    while (low < high)
    {
        // If both characters are equal then move both pointer
        // towards end
        if (str[low] == str[high])
        {
            low++;
            high--;
        }
        else
        {
            /*  If removing str[low] makes the whole string palindrome.
                We basically check if substring str[low+1..high] is
                palindrome or not. */
            if (isPalindrome(str.begin() + low + 1, str.begin() + high))
                return low;
  
            /*  If removing str[high] makes the whole string palindrome
                We basically check if substring str[low+1..high] is
                palindrome or not. */
            if (isPalindrome(str.begin() + low, str.begin() + high - 1))
                return high;
  
            return -1;
        }
    }
  
    //  We reach here when complete string will be palindrome
    //  if complete string is palindrome then return mid character
    return -2;
}
  
// Driver code to test above methods
int main()
{
    string str = "abecbea";
    int idx = possiblePalinByRemovingOneChar(str);
    if (idx == -1)
        cout << "Not Possible \n";
    else if (idx == -2)
        cout << "Possible without removing any character";
    else
        cout << "Possible by removing character"
             << " at index " << idx << "\n";
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to check whether 
// it is possible to make string 
// palindrome by removing one character
import java.util.*;
  
class GFG 
{
  
    // Utility method to check if 
    // substring from low to high is
    // palindrome or not.
    static boolean isPalindrome(String str, 
                       int low, int high)
    {
        while (low < high) 
        {
            if (str.charAt(low) != str.charAt(high))
                return false;
            low++;
            high--;
        }
        return true;
    }
  
    // 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.
    static int possiblePalinByRemovingOneChar(String str)
    {
  
        // Initialize low and right 
        // by both the ends of the string
        int low = 0, high = str.length() - 1;
  
        // loop untill low and
        // high cross each other
        while (low < high) 
        {
  
            // If both characters are equal then 
            // move both pointer towards end
            if (str.charAt(low) == str.charAt(high)) 
            {
                low++;
                high--;
            
            else
            {
  
                /*
                * If removing str[low] makes the 
                * whole string palindrome. We basically 
                * check if substring str[low+1..high]
                * is palindrome or not.
                */
                if (isPalindrome(str, low + 1, high))
                    return low;
  
                /*
                * If removing str[high] makes the whole string 
                * palindrome. We basically check if substring 
                * str[low+1..high] is palindrome or not.
                */
                if (isPalindrome(str, low, high - 1))
                    return high;
                return -1;
            }
        }
  
        // We reach here when complete string 
        // will be palindrome if complete string 
        // is palindrome then return mid character
        return -2;
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        String str = "abecbea";
        int idx = possiblePalinByRemovingOneChar(str);
  
        if (idx == -1)
            System.out.println("Not Possible");
        else if (idx == -2)
            System.out.println("Possible without "
                          "removing any character");
        else
            System.out.println("Possible by removing"
                               " character at index " + idx);
    }
}
  
// This code is contributed by
// sanjeev2552

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to check whether it is possible to make
# string palindrome by removing one character
  
# Utility method to check if substring from 
# low to high is palindrome or not.
def isPalindrome(string: str, low: int, high: int) -> bool:
    while low < high:
        if string[low] != string[high]:
            return False
        low += 1
        high -= 1
    return True
  
# 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.
def possiblepalinByRemovingOneChar(string: str) -> int:
  
    # Initialize low and right by
    # both the ends of the string
    low = 0
    high = len(string) - 1
  
    # loop untill low and high cross each other
    while low < high:
  
        # If both characters are equal then
        # move both pointer towards end
        if string[low] == string[high]:
            low += 1
            high -= 1
        else:
  
            # If removing str[low] makes the whole string palindrome.
            # We basically check if substring str[low+1..high] is
            # palindrome or not.
            if isPalindrome(string, low + 1, high):
                return low
  
            # If removing str[high] makes the whole string palindrome
            # We basically check if substring str[low+1..high] is
            # palindrome or not
            if isPalindrome(string, low, high - 1):
                return high
            return -1
  
    # We reach here when complete string will be palindrome
    # if complete string is palindrome then return mid character
    return -2
  
# Driver Code
if __name__ == "__main__":
  
    string = "abecbea"
    idx = possiblepalinByRemovingOneChar(string)
  
    if idx == -1:
        print("Not possible")
    elif idx == -2:
        print("Possible without removig any character")
    else:
        print("Possible by removing character at index", idx)
  
# This code is contributed by
# sanjeev2552

chevron_right


Output:

Not Possible 

This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details




My Personal Notes arrow_drop_up

Improved By : sanjeev2552

Article Tags :
Practice Tags :


2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.