Longest Palindrome in a String formed by concatenating its prefix and suffix
Last Updated :
26 Dec, 2022
Given a string str consisting of lowercase English letters, the task is to find the longest palindromic string T which satisfies the following condition:
- T = p + m + s where p and s are the prefix and the suffix of the given string str respectively and the string m is either the prefix or suffix of the string str after removing both p and s from it.
- The string formed by the concatenation of p and s is a palindrome itself.
- Either of the strings p and s can be an empty string.
Examples:
Input: str = "abcdfdcecba"
Output: abcdfdcba
Explanation:
Here, p = "abc"
s = "cba"
m = "dfd"
p + s = "abccba" which is a palindrome and m = "dfd" is the prefix after removing the prefix and suffix from the string str. Therefore, T = "abcdfdcba".
Input: str = "geeksforgeeks"
Output: g
Explanation:
Here, p = ""
s = "g"
m = ""
p + s = "" which is a palindrome and m = "g" is the prefix after removing the prefix and suffix from the string str. Therefore, T = "g".
Approach: The idea for this problem is to divide the answer into three parts, such that there will be a part of suffix and prefix of the given string which forms palindrome together which will form the beginning and the ending of the answer string. Now, after removing these prefix and suffix from the given string, we can find the maximum length suffix or prefix string (which we may call midPalindrome) which is palindromic.
Therefore, the answer string will be given by:
answer = prefix + midPalindrome + suffix
The following steps can be followed to compute the answer to the problem:
- Find the length up to which the suffix and prefix of str form a palindrome together.
- Remove the suffix and prefix substrings that already form a palindrome from str and store them in separate strings.
- Check all prefix and suffix substrings in the remaining string str and find the longest of such strings.
- Finally, combine all three parts of the answer and return it.
Below is the implementation of the above approach:
C++
// C++ program to find the longest
// palindrome in a string formed by
// concatenating its prefix and suffix
#include <bits/stdc++.h>
using namespace std;
// Function to check whether
// the string is a palindrome
bool isPalindrome(string r)
{
string p = r;
// Reverse the string to
// compare with the
// original string
reverse(p.begin(), p.end());
// Check if both are same
return (r == p);
}
// Function to find the longest
// palindrome in a string formed by
// concatenating its prefix and suffix
string PrefixSuffixPalindrome(string str)
{
// Length of the string
int n = str.size(), len = 0;
// Finding the length upto which
// the suffix and prefix forms a
// palindrome together
for (int i = 0; i < n / 2; i++) {
if (str[i] != str[n - i - 1]) {
len = i;
break;
}
}
// Check whether the string
// has prefix and suffix substrings
// which are palindromes.
string prefix = "", suffix = "";
string midPal = "";
// Removing the suffix and prefix
// substrings which already forms
// a palindrome and storing them
// in separate strings
prefix = str.substr(0, len);
suffix = str.substr(n - len);
str = str.substr(len, n - 2 * len);
// Check all prefix substrings
// in the remaining string str
for (int i = 1; i <= str.size(); i++) {
string y = str.substr(0, i);
// Check if the prefix substring
// is a palindrome
if (isPalindrome(y)) {
// If the prefix substring
// is a palindrome then check
// if it is of maximum length
// so far
if (midPal.size() < y.size()) {
midPal = y;
}
}
}
// Check all the suffix substrings
// in the remaining string str
for (int i = 1; i <= str.size(); i++) {
string y = str.substr(str.size() - i);
// Check if the suffix substring
// is a palindrome
if (isPalindrome(y)) {
// If the suffix substring
// is a palindrome then check
// if it is of maximum length
// so far
if (midPal.size() < y.size()) {
midPal = y;
}
}
}
// Combining all the three parts
// of the answer
string answer = prefix + midPal + suffix;
return answer;
}
// Driver code
int main()
{
string str = "abcdfdcecba";
cout << PrefixSuffixPalindrome(str) << "\n";
return 0;
}
Java
// Java program to find the longest
// palindrome in a String formed by
// concatenating its prefix and suffix
import java.util.*;
class GFG{
// Function to check whether
// the String is a palindrome
static boolean isPalindrome(String r)
{
String p = r;
// Reverse the String to
// compare with the
// original String
p = reverse(p);
// Check if both are same
return (r.equals(p));
}
// Function to find the longest
// palindrome in a String formed by
// concatenating its prefix and suffix
static String PrefixSuffixPalindrome(String str)
{
// Length of the String
int n = str.length(), len = 0;
// Finding the length upto which
// the suffix and prefix forms a
// palindrome together
for (int i = 0; i < n / 2; i++) {
if (str.charAt(i) != str.charAt(n - i - 1)) {
len = i;
break;
}
}
// Check whether the String
// has prefix and suffix subStrings
// which are palindromes.
String prefix = "", suffix = "";
String midPal = "";
// Removing the suffix and prefix
// subStrings which already forms
// a palindrome and storing them
// in separate Strings
prefix = str.substring(0, len);
suffix = str.substring(n - len);
str = str.substring(len, (n - 2 * len) + len);
// Check all prefix subStrings
// in the remaining String str
for (int i = 1; i <= str.length(); i++) {
String y = str.substring(0, i);
// Check if the prefix subString
// is a palindrome
if (isPalindrome(y)) {
// If the prefix subString
// is a palindrome then check
// if it is of maximum length
// so far
if (midPal.length() < y.length()) {
midPal = y;
}
}
}
// Check all the suffix subStrings
// in the remaining String str
for (int i = 1; i <= str.length(); i++) {
String y = str.substring(str.length() - i);
// Check if the suffix subString
// is a palindrome
if (isPalindrome(y)) {
// If the suffix subString
// is a palindrome then check
// if it is of maximum length
// so far
if (midPal.length() < y.length()) {
midPal = y;
}
}
}
// Combining all the parts
// of the answer
String answer = prefix + midPal + suffix;
return answer;
}
static String reverse(String input) {
char[] a = input.toCharArray();
int l, r = a.length - 1;
for (l = 0; l < r; l++, r--) {
char temp = a[l];
a[l] = a[r];
a[r] = temp;
}
return String.valueOf(a);
}
// Driver code
public static void main(String[] args)
{
String str = "abcdfdcecba";
System.out.print(PrefixSuffixPalindrome(str));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 program to find the longest
# palindrome in a string formed by
# concatenating its prefix and suffix
# Function to check whether
# the string is a palindrome
def isPalindrome(r):
p = r
# Reverse the string to
# compare with the
# original string
p = "".join(reversed(p))
# Check if both are same
return (r == p)
# Function to find the longest
# palindrome in a string formed by
# concatenating its prefix and suffix
def PrefixSuffixPalindrome(st):
# Length of the string
n = len(st)
length = 0
# Finding the length upto which
# the suffix and prefix forms a
# palindrome together
for i in range( n // 2):
if (st[i] != st[n - i - 1]):
length = i
break
# Check whether the string
# has prefix and suffix substrings
# which are palindromes.
prefix = ""
suffix = ""
midPal = ""
# Removing the suffix and prefix
# substrings which already forms
# a palindrome and storing them
# in separate strings
prefix = st[:length]
suffix = st[n - length:]
st = st[length: n - 2 * length+length]
# Check all prefix substrings
# in the remaining string str
for i in range(1,len(st)+1):
y = st[0: i]
# Check if the prefix substring
# is a palindrome
if (isPalindrome(y)):
# If the prefix substring
# is a palindrome then check
# if it is of maximum length
# so far
if (len(midPal) < len(y)):
midPal = y
# Check all the suffix substrings
# in the remaining string str
for i in range(1,len(st)+1):
y = st[len(st)-i]
# Check if the suffix substring
# is a palindrome
if (isPalindrome(y)):
# If the suffix substring
# is a palindrome then check
# if it is of maximum length
# so far
if (len(midPal) < len(y)):
midPal = y
# Combining all the parts
# of the answer
answer = prefix + midPal + suffix
return answer
# Driver code
if __name__ == "__main__":
st = "abcdfdcecba";
print(PrefixSuffixPalindrome(st))
# This code is contributed by chitranayal
C#
// C# program to find the longest
// palindrome in a String formed by
// concatenating its prefix and suffix
using System;
class GFG{
// Function to check whether
// the String is a palindrome
static bool isPalindrome(String r)
{
String p = r;
// Reverse the String to
// compare with the
// original String
p = reverse(p);
// Check if both are same
return (r.Equals(p));
}
// Function to find the longest
// palindrome in a String formed by
// concatenating its prefix and suffix
static String PrefixSuffixPalindrome(String str)
{
// Length of the String
int n = str.Length, len = 0;
// Finding the length upto which
// the suffix and prefix forms a
// palindrome together
for (int i = 0; i < n / 2; i++) {
if (str[i] != str[n - i - 1]) {
len = i;
break;
}
}
// Check whether the String
// has prefix and suffix subStrings
// which are palindromes.
String prefix = "", suffix = "";
String midPal = "";
// Removing the suffix and prefix
// subStrings which already forms
// a palindrome and storing them
// in separate Strings
prefix = str.Substring(0, len);
suffix = str.Substring(n - len);
str = str.Substring(len, (n - 2 * len) + len);
// Check all prefix subStrings
// in the remaining String str
for (int i = 1; i <= str.Length; i++) {
String y = str.Substring(0, i);
// Check if the prefix subString
// is a palindrome
if (isPalindrome(y)) {
// If the prefix subString
// is a palindrome then check
// if it is of maximum length
// so far
if (midPal.Length < y.Length) {
midPal = y;
}
}
}
// Check all the suffix subStrings
// in the remaining String str
for (int i = 1; i <= str.Length; i++) {
String y = str.Substring(str.Length - i);
// Check if the suffix subString
// is a palindrome
if (isPalindrome(y)) {
// If the suffix subString
// is a palindrome then check
// if it is of maximum length
// so far
if (midPal.Length < y.Length) {
midPal = y;
}
}
}
// Combining all the parts
// of the answer
String answer = prefix + midPal + suffix;
return answer;
}
static String reverse(String input) {
char[] a = input.ToCharArray();
int l, r = a.Length - 1;
for (l = 0; l < r; l++, r--) {
char temp = a[l];
a[l] = a[r];
a[r] = temp;
}
return String.Join("",a);
}
// Driver code
public static void Main(String[] args)
{
String str = "abcdfdcecba";
Console.Write(PrefixSuffixPalindrome(str));
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// Javascript program to find the longest
// palindrome in a String formed by
// concatenating its prefix and suffix
// Function to check whether
// the String is a palindrome
function isPalindrome(r)
{
let p = r;
// Reverse the String to
// compare with the
// original String
p = reverse(p);
// Check if both are same
return (r == (p));
}
// Function to find the longest
// palindrome in a String formed by
// concatenating its prefix and suffix
function PrefixSuffixPalindrome(str)
{
// Length of the String
let n = str.length, len = 0;
// Finding the length upto which
// the suffix and prefix forms a
// palindrome together
for (let i = 0; i < n / 2; i++) {
if (str[i] != str[n - i - 1]) {
len = i;
break;
}
}
// Check whether the String
// has prefix and suffix subStrings
// which are palindromes.
let prefix = "", suffix = "";
let midPal = "";
// Removing the suffix and prefix
// subStrings which already forms
// a palindrome and storing them
// in separate Strings
prefix = str.substring(0, len);
suffix = str.substring(n - len);
str = str.substring(len, (n - 2 * len) + len);
// Check all prefix subStrings
// in the remaining String str
for (let i = 1; i <= str.length; i++) {
let y = str.substring(0, i);
// Check if the prefix subString
// is a palindrome
if (isPalindrome(y)) {
// If the prefix subString
// is a palindrome then check
// if it is of maximum length
// so far
if (midPal.length < y.length) {
midPal = y;
}
}
}
// Check all the suffix subStrings
// in the remaining String str
for (let i = 1; i <= str.length; i++) {
let y = str.substring(str.length - i);
// Check if the suffix subString
// is a palindrome
if (isPalindrome(y)) {
// If the suffix subString
// is a palindrome then check
// if it is of maximum length
// so far
if (midPal.length < y.length) {
midPal = y;
}
}
}
// Combining all the parts
// of the answer
let answer = prefix + midPal + suffix;
return answer;
}
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 (a).join("");
}
// Driver code
let str = "abcdfdcecba";
document.write(PrefixSuffixPalindrome(str));
// This code is contributed by avanitrachhadiya2155
</script>
Time Complexity: O(n2)
Auxiliary Space: O(n), where n is the length of the given string.
Similar Reads
Longest palindromic string formed by concatenation of prefix and suffix of a string Given string str, the task is to find the longest palindromic substring formed by the concatenation of the prefix and suffix of the given string str. Examples: Input: str = "rombobinnimor" Output: rominnimor Explanation: The concatenation of string "rombob"(prefix) and "mor"(suffix) is "rombobmor" w
10 min read
Longest palindrome formed by concatenating and reordering strings of equal length Given an array arr[] consisting of N strings of equal length M, the task is to create the longest palindrome by concatenating the strings. Reordering and discarding some strings from the given set of strings can also be done.Examples: Input: N = 3, arr[] = { "tab", "one", "bat" }, M = 3 Output: tabb
9 min read
Longest palindromic string possible by concatenating strings from a given array Given an array of strings S[] consisting of N distinct strings of length M. The task is to generate the longest possible palindromic string by concatenating some strings from the given array. Examples: Input: N = 4, M = 3, S[] = {"omg", "bbb", "ffd", "gmo"}Output: omgbbbgmoExplanation: Strings "omg"
8 min read
Palindrome check for concatenation of Prefixes and Suffixes Given an integer N and an array of strings arr[], the task is to check whether the concatenation of prefixes and suffixes of all strings forms a palindrome or not. Examples: Input: N = 4, arr[] = {"bcd", "cd", "a", "d", "abc", "ab"}Output: NoExplanation: "a", "ab" and "abc" are prefixes. "d", "cd" a
8 min read
Lexicographically smallest string formed by concatenating any prefix and its mirrored form Given a string str of N characters, the task is to find the lexicographically smallest string that can be formed by concatenating any prefix and its mirrored form. Examples: Input: str = "geeksforgeeks"Output: geeeegExplanation: The lexicographically smallest string can be formed with the prefix "ge
5 min read