Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Longest palindromic string formed by concatenation of prefix and suffix of a string
Next article icon

Longest palindromic string possible by concatenating strings from a given array

Last Updated : 22 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
void max_len(string s[], int N, int M)
{
    // Stores the distinct strings
    // from the given array
    unordered_set<string> set_str;
 
    // Insert the strings into set
    for (int i = 0; i < N; i++) {
 
        set_str.insert(s[i]);
    }
 
    // Stores the left and right
    // substrings of the given string
    vector<string> left_ans, right_ans;
 
    // Stores the middle substring
    string mid;
 
    // Traverse the array of strings
    for (int i = 0; i < N; i++) {
 
        string t = s[i];
 
        // Reverse the current string
        reverse(t.begin(), t.end());
 
        // Checking if the string is
        // itself a palindrome or not
        if (t == s[i]) {
 
            mid = t;
        }
 
        // Check if the reverse of the
        // string is present or not
        else if (set_str.find(t)
                != set_str.end()) {
 
            // Append to the left substring
            left_ans.push_back(s[i]);
 
            // Append to the right substring
            right_ans.push_back(t);
 
            // Erase both the strings
            // from the set
            set_str.erase(s[i]);
            set_str.erase(t);
        }
    }
 
    // Print the left substring
    for (auto x : left_ans) {
 
        cout << x;
    }
 
    // Print the middle substring
    cout << mid;
 
    reverse(right_ans.begin(),
            right_ans.end());
 
    // Print the right substring
    for (auto x : right_ans) {
 
        cout << x;
    }
}
 
// Driver Code
int main()
{
    int N = 4, M = 3;
    string s[] = { "omg", "bbb",
                "ffd", "gmo" };
 
    // Function Call
    max_len(s, N, M);
 
    return 0;
}
 
 

Java




// Java program for the
// above approach
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)
{
  // Stores the distinct Strings
  // from the given array
  HashSet<String> set_str =
          new HashSet<>();
 
  // Insert the Strings
  // into set
  for (int i = 0; i < N; i++)
  {
    set_str.add(s[i]);
  }
 
  // Stores the left and right
  // subStrings of the given String
  Vector<String> left_ans =
                 new Vector<>();
  Vector<String> right_ans =
                 new Vector<>();
 
  // Stores the middle
  // subString
  String mid = "";
 
  // Traverse the array
  // of Strings
  for (int i = 0; i < N; i++)
  {
    String t = s[i];
 
    // Reverse the current
    // String
    t = reverse(t);
 
    // Checking if the String is
    // itself a palindrome or not
    if (t == s[i])
    {
      mid = t;
    }
 
    // Check if the reverse of the
    // String is present or not
    else if (set_str.contains(t))
    {
      // Append to the left
      // subString
      left_ans.add(s[i]);
 
      // Append to the right
      // subString
      right_ans.add(t);
 
      // Erase both the Strings
      // from the set
      set_str.remove(s[i]);
      set_str.remove(t);
    }
  }
 
  // Print the left subString
  for (String x : left_ans)
  {
    System.out.print(x);
  }
 
  // Print the middle
  // subString
  System.out.print(mid);
 
  Collections.reverse(right_ans);
  // Print the right subString
   
  for (String x : right_ans)
  {
    System.out.print(x);
  }
}
 
// Driver Code
public static void main(String[] args)
{
  int N = 4, M = 3;
  String s[] = {"omg", "bbb",
                "ffd", "gmo"};
 
  // Function Call
  max_len(s, N, M);
}
}
 
// This code is contributed by Rajput-Ji
 
 

Python3




# Python3 program for the above approach
def max_len(s, N, M):
     
    # Stores the distinct strings
    # from the given array
    set_str = {}
  
    # Insert the strings into set
    for i in s:
        set_str[i] = 1
  
    # Stores the left and right
    # substrings of the given string
    left_ans, right_ans = [], []
  
    # Stores the middle substring
    mid = ""
  
    # Traverse the array of strings
    for i in range(N):
        t = s[i]
  
        # Reverse the current string
        t = t[::-1]
  
        # Checking if the is
        # itself a palindrome or not
        if (t == s[i]):
            mid = t
  
        # Check if the reverse of the
        # is present or not
        elif (t in set_str):
  
            # Append to the left substring
            left_ans.append(s[i])
  
            # Append to the right substring
            right_ans.append(t)
  
            # Erase both the strings
            # from the set
            del set_str[s[i]]
            del set_str[t]
  
    # Print the left substring
    for x in left_ans:
        print(x, end = "")
  
    # Print the middle substring
    print(mid, end = "")
  
    right_ans = right_ans[::-1]
  
    # Print the right substring
    for x in right_ans:
        print(x, end = "")
  
# Driver Code
if __name__ == '__main__':
     
    N = 4
    M = 3
     
    s = [ "omg", "bbb", "ffd", "gmo"]
  
    # Function call
    max_len(s, N, M)
     
# This code is contributed by mohit kumar 29
 
 

C#




// C# program for the
// above approach
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)
{
  // Stores the distinct Strings
  // from the given array
  HashSet<String> set_str =
          new HashSet<String>();
 
  // Insert the Strings
  // into set
  for (int i = 0; i < N; i++)
  {
    set_str.Add(s[i]);
  }
 
  // Stores the left and right
  // subStrings of the given String
  List<String> left_ans =
       new List<String>();
  List<String> right_ans =
       new List<String>();
 
  // Stores the middle
  // subString
  String mid = "";
 
  // Traverse the array
  // of Strings
  for (int i = 0; i < N; i++)
  {
    String t = s[i];
 
    // Reverse the current
    // String
    t = reverse(t);
 
    // Checking if the String is
    // itself a palindrome or not
    if (t == s[i])
    {
      mid = t;
    }
 
    // Check if the reverse of the
    // String is present or not
    else if (set_str.Contains(t))
    {
      // Append to the left
      // subString
      left_ans.Add(s[i]);
 
      // Append to the right
      // subString
      right_ans.Add(t);
 
      // Erase both the Strings
      // from the set
      set_str.Remove(s[i]);
      set_str.Remove(t);
    }
  }
 
  // Print the left subString
  foreach (String x in left_ans)
  {
    Console.Write(x);
  }
 
  // Print the middle
  // subString
  Console.Write(mid);
 
  right_ans.Reverse();
  // Print the right subString
 
  foreach (String x in right_ans)
  {
    Console.Write(x);
  }
}
 
// Driver Code
public static void Main(String[] args)
{
  int N = 4, M = 3;
  String []s = {"omg", "bbb",
                "ffd", "gmo"};
 
  // Function Call
  max_len(s, N, M);
}
}
 
// This code is contributed by 29AjayKumar
 
 

Javascript




<script>
// Javascript program for the
// above approach
 
function reverse(input)
{
    let a = input.split("");
    a.reverse();
    return a.join("");
}
 
function max_len(s, N, M)
{
 
    // Stores the distinct Strings
  // from the given array
  let set_str = new Set();
  
  // Insert the Strings
  // into set
  for (let i = 0; i < N; i++)
  {
    set_str.add(s[i]);
  }
  
  // Stores the left and right
  // subStrings of the given String
  let left_ans = [];
   
  let right_ans = [];
  
  // Stores the middle
  // subString
  let mid = "";
  
  // Traverse the array
  // of Strings
  for (let i = 0; i < N; i++)
  {
    let t = s[i];
  
    // Reverse the current
    // String
    t = reverse(t);
  
    // Checking if the String is
    // itself a palindrome or not
    if (t == s[i])
    {
      mid = t;
    }
  
    // Check if the reverse of the
    // String is present or not
    else if (set_str.has(t))
    {
      // Append to the left
      // subString
      left_ans.push(s[i]);
  
      // Append to the right
      // subString
      right_ans.push(t);
  
      // Erase both the Strings
      // from the set
      set_str.delete(s[i]);
      set_str.delete(t);
    }
  }
  
  // Print the left subString
  for (let x=0;x< left_ans.length;x++)
  {
    document.write(left_ans[x]);
  }
  
  // Print the middle
  // subString
  document.write(mid);
  
  (right_ans).reverse();
  // Print the right subString
    
  for (let x = 0; x < right_ans.length; x++)
  {
    document.write(right_ans[x]);
  }
}
 
// Driver Code
 
let N = 4, M = 3;
let s=["omg", "bbb",
                "ffd", "gmo"];
// Function Call
max_len(s, N, M);
 
// This code is contributed by patel2127
</script>
 
 

Output:

omgbbbgmo

Time Complexity: O(N * M)
Auxiliary Space: O(N * M)



Next Article
Longest palindromic string formed by concatenation of prefix and suffix of a string

M

mohitpandey3
Improve
Article Tags :
  • Arrays
  • DSA
  • Hash
  • Strings
  • cpp-set
  • Reverse
  • substring
Practice Tags :
  • Arrays
  • Hash
  • Reverse
  • Strings

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
    11 min read
  • Longest Palindrome in a String formed by concatenating its prefix and suffix
    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
    13 min read
  • Largest palindromic string possible from given strings by rearranging the characters
    Given two strings S and P, the task is to find the largest palindrome possible string by choosing characters from the given strings S and P after rearranging the characters. Note: If many answers are possible, then find the lexicographically smallest T with maximum length. Examples: Input: S = "abad
    13 min read
  • Palindromic strings of length 3 possible by using characters of a given string
    Given a string S consisting of N characters, the task is to print all palindromic strings of length 3 in lexicographical order that can be formed using characters of the given string S. Examples: Input: S = "aabc"Output:abaaca Input: S = "ddadbac"Output:abaacaadadaddbddcdddd Approach: The given prob
    9 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
  • Maximize length of the String by concatenating characters from an Array of Strings
    Find the largest possible string of distinct characters formed using a combination of given strings. Any given string has to be chosen completely or not to be chosen at all. Examples: Input: strings ="abcd", "efgh", "efgh" Output: 8Explanation: All possible combinations are {"", "abcd", "efgh", "abc
    12 min read
  • All possible strings of any length that can be formed from a given string
    Given a string of distinct characters, print all possible strings of any length that can be formed from given string characters. Examples: Input: abcOutput: a b c abc ab ac bc bac bca cb ca ba cab cba acbInput: abcdOutput: a b ab ba c ac ca bc cb abc acb bac bca cab cba d ad da bd db abd adb bad bda
    10 min read
  • Longest substring of 0s in a string formed by k concatenations
    Given a binary string of length n and an integer k. Consider another string T which is formed by concatenating the given binary string k times. The task is to print the maximum size of a substring of T containing only zeroes. Examples: Input: str = 110010, k = 3 Output: 2 str = 110010 T = 1100101100
    8 min read
  • Longest palindromic string possible after removal of a substring
    Given a string str, the task is to find the longest palindromic string that can be obtained from it after removing a substring. Examples: Input: str = "abcdefghiedcba" Output: "abcdeiedcba" Explanation: Removal of substring "fgh" leaves the remaining string palindromic Input: str = "abba" Output: "a
    11 min read
  • Maximize palindromic strings of length 3 possible from given count of alphabets
    Given an array arr[] of size 26, representing frequencies of character 'a' to 'z', the task is to find the maximum number of palindromic strings of length 3 that can be generated from the specified count of alphabets. Examples: Input: arr[] = {4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences