Longest palindromic String formed using concatenation of given strings in any order

Given an array of strings arr[] of the same length, the task is to find the longest palindromic string that can be made using the concatenation of strings in any order.

Examples:

Input: arr[] = {“aba”, “aba”}
Output: abaaba



Input: arr[] = {“abc”, “dba”, “kop”, “cba”, “abd”}
Output: abcdbaabdcba

Approach:

  • Find all the pairs of strings which are reverse of each other and store them in two different arrays pair1[] and pair2 separately and delete those pairs from the original array.
  • Find any palindromic string s1 in the array.
  • Join all the strings together of the array pair1[] into s2
  • Join all the strings together of the array pair2[] in reverse order into s3
  • Concatenate the strings s2 + s1 + s3 together to get longest palindromic string.

Below is the implementation of the above approach.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implmentation to find the longest
// palindromic String formed using
// concatenation of given strings in any order
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the longest palindromic
// from given array of strings
void longestPalindrome(string a[],
                       int n)
{
    string pair1[n];
    string pair2[n];
    int r = 0;
  
    // Loop to find the pair of strings
    // which are reverse of each other
    for (int i = 0; i < n; i++) {
        string s = a[i];
        reverse(s.begin(), s.end());
        for (int j = i + 1; j < n; j++) {
            if (a[i] != "" && a[j] != "") {
                if (s == a[j]) {
                    pair1[r] = a[i];
                    pair2[r++] = a[j];
                    a[i] = "";
                    a[j] = "";
                    break;
                }
            }
        }
    }
    string s1 = "";
  
    // Loop to find if any palindromic
    // string is still left in the array
    for (int i = 0; i < n; i++) {
        string s = a[i];
        reverse(a[i].begin(), a[i].end());
        if (a[i] != "") {
            if (a[i] == s) {
                s1 = a[i];
                break;
            }
        }
    }
    string ans = "";
  
    // Update the answer with
    // all strings of pair1
    for (int i = 0; i < r; i++) {
        ans = ans + pair1[i];
    }
    // Update the answer with
    // palindromic string s1
    if (s1 != "") {
        ans = ans + s1;
    }
    // Update the answer with
    // all strings of pair2
    for (int j = r - 1; j >= 0; j--) {
        ans = ans + pair2[j];
    }
    cout << ans << endl;
}
  
// Driver Code
int main()
{
    string a1[2] = { "aba", "aba" };
    int n1 = sizeof(a1) / sizeof(a1[0]);
    longestPalindrome(a1, n1);
  
    string a2[5] = { "abc", "dba", "kop",
                     "abd", "cba" };
    int n2 = sizeof(a2) / sizeof(a2[0]);
    longestPalindrome(a2, n2);
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implmentation to find the longest
// palindromic String formed using
// concatenation of given Strings in any order
class GFG
{
  
// Function to find the longest palindromic
// from given array of Strings
static void longestPalindrome(String a[],
                            int n)
{
    String []pair1 = new String[n];
    String []pair2 = new String[n];
    int r = 0;
  
    // Loop to find the pair of Strings
    // which are reverse of each other
    for (int i = 0; i < n; i++)
    {
        String s = a[i];
        s = reverse(s);
        for (int j = i + 1; j < n; j++) 
        {
            if (a[i] != "" && a[j] != "")
            {
                if (s.equals(a[j])) 
                {
                    pair1[r] = a[i];
                    pair2[r++] = a[j];
                    a[i] = "";
                    a[j] = "";
                    break;
                }
            }
        }
    }
    String s1 = "";
  
    // Loop to find if any palindromic
    // String is still left in the array
    for (int i = 0; i < n; i++) 
    {
        String s = a[i];
        a[i] = reverse(a[i]);
        if (a[i] != ""
        {
            if (a[i].equals(s))
            {
                s1 = a[i];
                break;
            }
        }
    }
    String ans = "";
  
    // Update the answer with
    // all Strings of pair1
    for (int i = 0; i < r; i++)
    {
        ans = ans + pair1[i];
    }
      
    // Update the answer with
    // palindromic String s1
    if (s1 != "")
    {
        ans = ans + s1;
    }
    // Update the answer with
    // all Strings of pair2
    for (int j = r - 1; j >= 0; j--) 
    {
        ans = ans + pair2[j];
    }
    System.out.print(ans +"\n");
}
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 []a1 = { "aba", "aba" };
    int n1 = a1.length;
    longestPalindrome(a1, n1);
  
    String []a2 = { "abc", "dba", "kop",
                    "abd", "cba" };
    int n2 = a2.length;
    longestPalindrome(a2, n2);
}
}
  
// This code is contributed by Rajput-Ji

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implmentation to find the longest
# palindromic String formed using
# concatenation of given strings in any order
  
# Function to find the longest palindromic
# from given array of strings
def longestPalindrome(a, n):
    pair1 = [0]*n
    pair2 = [0]*n
    r = 0
  
    # Loop to find the pair of strings
    # which are reverse of each other
    for i in range(n):
        s = a[i]
        s = s[::-1]
        for j in range(i + 1, n):
            if (a[i] != "" and a[j] != ""):
                if (s == a[j]):
                    pair1[r] = a[i]
                    pair2[r] = a[j]
                    r += 1
                    a[i] = ""
                    a[j] = ""
                    break
  
    s1 = ""
  
    # Loop to find if any palindromic
    # is still left in the array
    for i in range(n):
        s = a[i]
        a[i] = a[i][::-1]
        if (a[i] != ""):
            if (a[i] == s):
                s1 = a[i]
                break
  
    ans = ""
  
    # Update the answer with
    # all strings of pair1
    for i in range(r):
        ans = ans + pair1[i]
      
    # Update the answer with
    # palindromic s1
    if (s1 != ""):
        ans = ans + s1
      
    # Update the answer with
    # all strings of pair2
    for j in range(r - 1, -1, -1):
        ans = ans + pair2[j]
    print(ans)
  
# Driver Code
a1 = ["aba", "aba"]
n1 = len(a1)
longestPalindrome(a1, n1)
  
a2 = ["abc", "dba", "kop","abd", "cba"]
n2 = len(a2)
longestPalindrome(a2, n2)
  
# This code is contributed by mohit kumar 29

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implmentation to find the longest
// palindromic String formed using
// concatenation of given Strings in any order
using System;
  
class GFG
{
   
// Function to find the longest palindromic
// from given array of Strings
static void longestPalindrome(String []a,
                            int n)
{
    String []pair1 = new String[n];
    String []pair2 = new String[n];
    int r = 0;
   
    // Loop to find the pair of Strings
    // which are reverse of each other
    for (int i = 0; i < n; i++)
    {
        String s = a[i];
        s = reverse(s);
        for (int j = i + 1; j < n; j++) 
        {
            if (a[i] != "" && a[j] != "")
            {
                if (s.Equals(a[j])) 
                {
                    pair1[r] = a[i];
                    pair2[r++] = a[j];
                    a[i] = "";
                    a[j] = "";
                    break;
                }
            }
        }
    }
    String s1 = "";
   
    // Loop to find if any palindromic
    // String is still left in the array
    for (int i = 0; i < n; i++) 
    {
        String s = a[i];
        a[i] = reverse(a[i]);
        if (a[i] != ""
        {
            if (a[i].Equals(s))
            {
                s1 = a[i];
                break;
            }
        }
    }
    String ans = "";
   
    // Update the answer with
    // all Strings of pair1
    for (int i = 0; i < r; i++)
    {
        ans = ans + pair1[i];
    }
       
    // Update the answer with
    // palindromic String s1
    if (s1 != "")
    {
        ans = ans + s1;
    }
    // Update the answer with
    // all Strings of pair2
    for (int j = r - 1; j >= 0; j--) 
    {
        ans = ans + pair2[j];
    }
    Console.Write(ans +"\n");
}
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 []a1 = { "aba", "aba" };
    int n1 = a1.Length;
    longestPalindrome(a1, n1);
   
    String []a2 = { "abc", "dba", "kop",
                    "abd", "cba" };
    int n2 = a2.Length;
    longestPalindrome(a2, n2);
}
}
  
// This code is contributed by 29AjayKumar

chevron_right


Output:

abaaba
abcdbaabdcba



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.