Open In App

Return a Palindromic String after removing minimum length Prefix from given String

Improve
Improve
Like Article
Like
Save
Share
Report

Given a string B, the task is to find the minimum length prefix of the string which, when removed and added to the end of the string, will make the string a palindrome. Return the palindromic string. If no such string exists, we need to determine that.

Examples:

Input: “aabb”
Output: “abba”
Explanation: We can remove the prefix “a” from the string “aabb” and add it to the end of the string to get “abba”, which is a palindrome.

Input: “abcde”
Output: “NO SUCH STRING”
Explanation: There is no prefix of the string “abcde” which, when removed and added to the end of the string, will make the string a palindrome.

Approach: To solve the problem follow the below idea:

The basic idea is to check if the string is already a palindrome. If it is, then don’t need to do anything. If it is not a palindrome, try removing the minimum length prefix and adding it to the end of the string to see if that makes the string a palindrome. 

Follow the below steps to approach the problem:

  • Check if the given string is already a palindrome. If it is, return the string.
  • If the string is not a palindrome, try removing the minimum length prefix of the string and adding it to the end of the string to see if that makes the string a palindrome.
  • If the modified string is a palindrome, return it.
    •  If not, try removing a longer prefix and adding it to the end of the string.
    • check if that makes the string a palindrome
    • Repeat this process until all possible prefixes are checked.
  • If no solution was found, return “NO SUCH STRING”.

Below is the Implementation of the above approach:

C++14




// C++ code implementation
 
#include <bits/stdc++.h>
using namespace std;
 
bool isPalindrome(string str)
{
    // check if the string is a palindrome
    string rev_str=str;
    reverse(rev_str.begin(), rev_str.end());
    return str==rev_str;
}
 
string makePalindrome(string str)
{
    if (isPalindrome(str)) {
        // string is already a palindrome,
        // so we don't need to do anything
        return str;
    }
 
    for (int i = 1; i <= str.length(); ++i) {
      // remove the prefix of length i
      // from the string
      string prefix = str.substr(0, i);
      string modifiedString
        = str.substr(i) + prefix;
     
      if (isPalindrome(modifiedString)) {
        // modifiedString is a palindrome,
        // so we found the solution
        return modifiedString;
      }
    }
     
    // we couldn't find a solution
    return "NO SUCH STRING";
}
 
int main()
{
    cout<<(makePalindrome("aabb"))<<endl;
    cout<<(makePalindrome("abcba"))<<endl;
    cout<<(makePalindrome("abcde"))<<endl;
    cout<<(makePalindrome("abb"))<<endl;
    cout<<(makePalindrome("aab"))<<endl;
    return 0;
}


Java




// Java code implementation
import java.io.*;
 
class GFG {
 
  static boolean isPalindrome(String str)
  {
    // check if the string is a palindrome
    return str.equals(
      new StringBuilder(str).reverse().toString());
  }
 
  static String makePalindrome(String string)
  {
    if (isPalindrome(string)) {
      // string is already a palindrome,
      // so we don't need to do anything
      return string;
    }
 
    for (int i = 1; i <= string.length(); ++i) {
      // remove the prefix of length i
      // from the string
      String prefix = string.substring(0, i);
      String modifiedString
        = string.substring(i) + prefix;
 
      if (isPalindrome(modifiedString)) {
        // modifiedString is a palindrome,
        // so we found the solution
        return modifiedString;
      }
    }
 
    // we couldn't find a solution
    return "NO SUCH STRING";
  }
 
  public static void main(String[] args)
  {
    System.out.println(makePalindrome("aabb"));
    System.out.println(makePalindrome("abcba"));
    System.out.println(makePalindrome("abcde"));
    System.out.println(makePalindrome("abb"));
    System.out.println(makePalindrome("aab"));
  }
}
 
// This code is contributed by lokesh.


Python3




def make_palindrome(string):
    def is_palindrome(string):
 
        # check if the string is a palindrome
        return string == string[::-1]
 
    if is_palindrome(string):
 
        # string is already a palindrome,
        # so we don't need to do anything
        return string
 
    for i in range(1, len(string)):
 
        # remove the prefix of length i
        # from the string
        prefix = string[:i]
        modified_string = string[i:] + prefix
 
        if is_palindrome(modified_string):
 
            # modified_string is a palindrome,
            # so we found the solution
            return modified_string
 
    # we couldn't find a solution
    return "NO SUCH STRING"
 
 
print(make_palindrome("aabb"))
print(make_palindrome("abcba"))
print(make_palindrome("abcde"))
print(make_palindrome("abb"))
print(make_palindrome("aab"))


C#




// C# code implementation
using System;
using System.Linq;
 
public class GFG
{
    static bool IsPalindrome(string str)
    {
        // check if the string is a palindrome
        return str.Equals(new string(str.Reverse().ToArray()));
    }
 
    static string MakePalindrome(string str)
    {
        bool isPalindrome = IsPalindrome(str);
 
        if (isPalindrome)
        {
            // string is already a palindrome,
            // so we don't need to do anything
            return str;
        }
 
        for (int i = 1; i <= str.Length; ++i)
        {
            // remove the prefix of length i
            // from the string
            string prefix = str.Substring(0, i);
            string modifiedStr = str.Substring(i) + prefix;
 
            if (IsPalindrome(modifiedStr))
            {
                // modifiedStr is a palindrome,
                // so we found the solution
                return modifiedStr;
            }
        }
 
        // we couldn't find a solution
        return "NO SUCH STRING";
    }
 
    static void Main(string[] args)
    {
        Console.WriteLine(MakePalindrome("aabb"));
        Console.WriteLine(MakePalindrome("abcba"));
        Console.WriteLine(MakePalindrome("abcde"));
        Console.WriteLine(MakePalindrome("abb"));
        Console.WriteLine(MakePalindrome("aab"));
    }
}
// This code is contributed by rutikbhosale


Javascript




<script>
 
    // JavaScript implementation
    const make_palindrome = (string) => {
        const is_palindrome = (string) => {
 
            // check if the string is a palindrome
            return string == string.split("").reverse().join("");
        }
 
        if (is_palindrome(string))
 
            // string is already a palindrome,
            // so we don't need to do anything
            return string
 
        for (let i = 1; i <= string.length; ++i) {
 
            // remove the prefix of length i
            // from the string
            prefix = string.substring(0, i);
            modified_string = string.substring(i) + prefix
 
            if (is_palindrome(modified_string))
 
                // modified_string is a palindrome,
                // so we found the solution
                return modified_string
        }
 
        // we couldn't find a solution
        return "NO SUCH STRING"
    }
 
    document.write(`${make_palindrome("aabb")}<br/>`);
    document.write(`${make_palindrome("abcba")}<br/>`);
    document.write(`${make_palindrome("abcde")}<br/>`);
    document.write(`${make_palindrome("abb")}<br/>`);
    document.write(`${make_palindrome("aab")}<br/>`);
 
    // This code is contributed by rakeshsahni
</script>


Output

abba
abcba
NO SUCH STRING
bab
aba

Time Complexity: O(N2), where N is the length of the string. This is because we are trying all possible prefixes of the string and checking if each one, when removed and added to the end of the string, makes the string a palindrome.
Auxiliary Space: O(1)

Related Articles:



Last Updated : 23 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads