Longest palindromic string possible by concatenating strings from a given array
Last Updated :
22 Jun, 2021
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: omgbbbgmo
Explanation: Strings “omg” and “gmo” are reverse of each other and “bbb” is itself a palindrome. Therefore, concatenating “omg” + “bbb” + “gmo” generates the longest palindromic string “omgbbbgmo”.
Input: N = 4, M = 3, s[]={“poy”, “fgh”, “hgf”, “yop”}
Output: poyfghhgfyop
Approach: Follow the steps below to solve the problem:
- Initialize a Set and insert each string from the given array in the Set.
- Initialize two vectors left_ans and right_ans to keep track of palindromic strings obtained.
- Now, iterate over the array of strings and check if its reverse exists in the Set or not.
- If found to be true, insert one of the strings into left_ans and the other into right_ans and erase both the strings from the Set to avoid repetition.
- If a string is a palindrome and its pair does not exist in the Set, then that string needs to be appended to the middle of the resultant string.
- Print the resultant string.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void max_len(string s[], int N, int M)
{
unordered_set<string> set_str;
for ( int i = 0; i < N; i++) {
set_str.insert(s[i]);
}
vector<string> left_ans, right_ans;
string mid;
for ( int i = 0; i < N; i++) {
string t = s[i];
reverse(t.begin(), t.end());
if (t == s[i]) {
mid = t;
}
else if (set_str.find(t)
!= set_str.end()) {
left_ans.push_back(s[i]);
right_ans.push_back(t);
set_str.erase(s[i]);
set_str.erase(t);
}
}
for ( auto x : left_ans) {
cout << x;
}
cout << mid;
reverse(right_ans.begin(),
right_ans.end());
for ( auto x : right_ans) {
cout << x;
}
}
int main()
{
int N = 4, M = 3;
string s[] = { "omg" , "bbb" ,
"ffd" , "gmo" };
max_len(s, N, M);
return 0;
}
|
Java
import java.util.*;
class GFG{
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);
}
static void max_len(String s[],
int N, int M)
{
HashSet<String> set_str =
new HashSet<>();
for ( int i = 0 ; i < N; i++)
{
set_str.add(s[i]);
}
Vector<String> left_ans =
new Vector<>();
Vector<String> right_ans =
new Vector<>();
String mid = "" ;
for ( int i = 0 ; i < N; i++)
{
String t = s[i];
t = reverse(t);
if (t == s[i])
{
mid = t;
}
else if (set_str.contains(t))
{
left_ans.add(s[i]);
right_ans.add(t);
set_str.remove(s[i]);
set_str.remove(t);
}
}
for (String x : left_ans)
{
System.out.print(x);
}
System.out.print(mid);
Collections.reverse(right_ans);
for (String x : right_ans)
{
System.out.print(x);
}
}
public static void main(String[] args)
{
int N = 4 , M = 3 ;
String s[] = { "omg" , "bbb" ,
"ffd" , "gmo" };
max_len(s, N, M);
}
}
|
Python3
def max_len(s, N, M):
set_str = {}
for i in s:
set_str[i] = 1
left_ans, right_ans = [], []
mid = ""
for i in range (N):
t = s[i]
t = t[:: - 1 ]
if (t = = s[i]):
mid = t
elif (t in set_str):
left_ans.append(s[i])
right_ans.append(t)
del set_str[s[i]]
del set_str[t]
for x in left_ans:
print (x, end = "")
print (mid, end = "")
right_ans = right_ans[:: - 1 ]
for x in right_ans:
print (x, end = "")
if __name__ = = '__main__' :
N = 4
M = 3
s = [ "omg" , "bbb" , "ffd" , "gmo" ]
max_len(s, N, M)
|
C#
using System;
using System.Collections.Generic;
class GFG{
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);
}
static void max_len(String []s,
int N, int M)
{
HashSet<String> set_str =
new HashSet<String>();
for ( int i = 0; i < N; i++)
{
set_str.Add(s[i]);
}
List<String> left_ans =
new List<String>();
List<String> right_ans =
new List<String>();
String mid = "" ;
for ( int i = 0; i < N; i++)
{
String t = s[i];
t = reverse(t);
if (t == s[i])
{
mid = t;
}
else if (set_str.Contains(t))
{
left_ans.Add(s[i]);
right_ans.Add(t);
set_str.Remove(s[i]);
set_str.Remove(t);
}
}
foreach (String x in left_ans)
{
Console.Write(x);
}
Console.Write(mid);
right_ans.Reverse();
foreach (String x in right_ans)
{
Console.Write(x);
}
}
public static void Main(String[] args)
{
int N = 4, M = 3;
String []s = { "omg" , "bbb" ,
"ffd" , "gmo" };
max_len(s, N, M);
}
}
|
Javascript
<script>
function reverse(input)
{
let a = input.split( "" );
a.reverse();
return a.join( "" );
}
function max_len(s, N, M)
{
let set_str = new Set();
for (let i = 0; i < N; i++)
{
set_str.add(s[i]);
}
let left_ans = [];
let right_ans = [];
let mid = "" ;
for (let i = 0; i < N; i++)
{
let t = s[i];
t = reverse(t);
if (t == s[i])
{
mid = t;
}
else if (set_str.has(t))
{
left_ans.push(s[i]);
right_ans.push(t);
set_str. delete (s[i]);
set_str. delete (t);
}
}
for (let x=0;x< left_ans.length;x++)
{
document.write(left_ans[x]);
}
document.write(mid);
(right_ans).reverse();
for (let x = 0; x < right_ans.length; x++)
{
document.write(right_ans[x]);
}
}
let N = 4, M = 3;
let s=[ "omg" , "bbb" ,
"ffd" , "gmo" ];
max_len(s, N, M);
</script>
|
Output:
omgbbbgmo
Time Complexity: O(N * M)
Auxiliary Space: O(N * M)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...