Skip to content
Related Articles

Related Articles

Improve Article
Make a string non-palindromic by inserting a given character
  • Difficulty Level : Expert
  • Last Updated : 14 May, 2021

Given a string S and a character X, the task is to generate a non-palindromic string by inserting the character X in the string S. If it is not possible to obtain a non-palindromic string, then print “-1”.

Examples:

Input: S = “ababab”, X = ‘a’
Output: “aababab”
Explanation: Inserting the character ‘a’ at the beginning of the string S modifies the string to “aababab”, which is non-palindromic.

Input: S = “rrr”, X = ‘r’
Output: -1

Approach: The given problem can be solved based on the following observation that if the string contains only character X, then it is impossible to make the string non-palindromic. Otherwise, the string can be made non-palindromic. Follow the steps below to solve the problem:



  1. If the count of character X in the string S is the same as the length of the string S, then print “-1”.
  2. Otherwise, check if concatenations of string S and character X is palindromic or not. If found to be true, then print the string S + X. Otherwise print (X + S).

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if a
// string is palindromic or not
bool Palindrome(string str)
{
    // Traverse the string str
    for (int i = 0, j = str.length() - 1;
         i < j; i++, j--) {
 
        // Check if i-th character from
        // both ends are the same or not
        if (str[i] != str[j])
            return false;
    }
 
    // Return true, as str is palindrome
    return true;
}
 
// Function to make the non-palindromic
// string by inserting the character X
void NonPalindrome(string str, char X)
{
 
    // If all the characters
    // in the string are X
    if (count(str.begin(), str.end(), X)
        == str.length()) {
 
        cout << "-1";
        return;
    }
 
    // Check if X + str is
    // palindromic or not
    if (Palindrome(X + str))
        cout << str + X << endl;
    else
        cout << X + str << endl;
}
 
// Driver Code
int main()
{
    string S = "geek";
    char X = 's';
    NonPalindrome(S, X);
 
    return 0;
}


Java




// java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
public class GFG {
 
    // Function to check if a
    // string is palindromic or not
    static boolean Palindrome(String str)
    {
        // Traverse the string str
        for (int i = 0, j = str.length() - 1; i < j;
             i++, j--) {
 
            // Check if i-th character from
            // both ends are the same or not
            if (str.charAt(i) != str.charAt(j))
                return false;
        }
 
        // Return true, as str is palindrome
        return true;
    }
 
    // Function to make the non-palindromic
    // string by inserting the character X
    static void NonPalindrome(String str, char X)
    {
 
        // stores the count of char X in str
        int count = 0;
        for (int i = 0; i < str.length(); i++)
            if (str.charAt(i) == X)
                count++;
 
        // If all the characters
        // in the string are X
        if (count == str.length()) {
 
            System.out.println("-1");
            return;
        }
 
        // Check if X + str is
        // palindromic or not
        if (Palindrome(X + str))
            System.out.println(str + X);
        else
            System.out.println(X + str);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        String S = "geek";
        char X = 's';
        NonPalindrome(S, X);
    }
}
 
// This code is contributed by Kingash.


Python3




# Python3 program for the above approach
 
# Function to check if a
# string is palindromic or not
def Palindrome(str):
     
    if str == str[::-1]:
        return True
 
    # Return true, as str is palindrome
    return False
 
# Function to make the non-palindromic
# string by inserting the character X
def NonPalindrome(str, X):
 
    # If all the characters
    # in the string are X
    if (str.count(X) == len(str)):
        print("-1")
        return
 
    # Check if X + str is
    # palindromic or not
    if (Palindrome(X + str)):
        print(str + X)
    else:
        print(X + str)
 
# Driver Code
if __name__ == '__main__':
     
    S = "geek"
    X = 's'
     
    NonPalindrome(S, X)
 
# This code is contributed by mohit kumar 29


C#




// C# program for the above approach
 
using System;
using System.Linq;
class GFG {
    // Function to check if a
    // string is palindromic or not
    static bool Palindrome(string str)
    {
        // Traverse the string str
        for (int i = 0, j = str.Length - 1; i < j;
             i++, j--) {
 
            // Check if i-th character from
            // both ends are the same or not
            if (str[i] != str[j])
                return false;
        }
 
        // Return true, as str is palindrome
        return true;
    }
 
    // Function to make the non-palindromic
    // string by inserting the character X
    static void NonPalindrome(string str, char X)
    {
 
        // If all the characters
        // in the string are X
        if (str.Count(p => p == X) == str.Length) {
 
            Console.Write("-1");
            return;
        }
 
        // Check if X + str is
        // palindromic or not
        if (Palindrome(X + str))
            Console.WriteLine(str + X);
        else
            Console.WriteLine(X + str);
    }
 
    // Driver Code
    public static void Main()
    {
        string S = "geek";
        char X = 's';
        NonPalindrome(S, X);
    }
}
 
// This code is contributed by ukasp.


Javascript




<script>
 
// javascript program for the above approach
 
// Function to check if a
// string is palindromic or not
function Palindrome( str)
{
    // Traverse the string str
    for (let i = 0, j = str.length - 1; i < j;
        i++, j--) {
 
        // Check if i-th character from
        // both ends are the same or not
        if (str.charAt(i) != str.charAt(j))
            return false;
    }
 
    // Return true, as str is palindrome
    return true;
}
 
// Function to make the non-palindromic
// string by inserting the character X
function NonPalindrome( str, X)
{
 
    // stores the count of char X in str
    var count = 0;
    for (let i = 0; i < str.length; i++)
        if (str.charAt(i) == X)
            count++;
 
    // If all the characters
    // in the string are X
    if (count == str.length) {
 
        document.write("-1");
        return;
    }
 
    // Check if X + str is
    // palindromic or not
    if (Palindrome(X + str))
        document.write(str + X);
    else
        document.write(X + str);
}
 
 
// Driver Code
 
var S = "geek";
var X = 's';
NonPalindrome(S, X);
 
</script>


Output:

sgeek

Time Complexity: O(N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer DSA Live Classes 




My Personal Notes arrow_drop_up
Recommended Articles
Page :