Print all possible palindromic string formed using any pair of given strings
Last Updated :
05 Aug, 2021
Given an array of strings arr[] containing N words, the task is to print all possible palindromic string by combining any two strings from the given array.
Examples:
Input: arr[] = ["geekf", "geeks", "or", "keeg", "abc", "ba"]
Output: ["geekfkeeg", "geekskeeg", "abcba"]
Explanation:
Below pairs forms the palindromic string on combining:
1. "geekf" + "keeg" = "geekfkeeg"
2. "geeks" + "keeg" = "geekskeeg"
3. "abc" + "ba" = "abcba"
Input: arr[] = ["dcb", "yz", "xy", "efg", "yx"]
Output: ["xyyx", "yxxy"]
Explanation:
1. "xy" + "yz" = "xyyz"
2. "yx" + "xy" = "yxxy"
Naive Approach: The naive approach is to iterate all possible pairs in the given array of strings and check whether concatenation of the string forms palindromic or not. If yes then print that pair and check for the next pairs.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized using Hashing. Below are the steps:
- Store all the words in a Map with words as keys and indices as values.
- For each word(say str) in the arr[] break the string into string s1 and s2 such that s1 + s2 = str.
- After the above step there arise two cases:
- Case 1: If s1 is a palindromic string and the reverse of s2 is present in the hash-map then we get the required pair (reverse of s2 + current word).
- Case 2: If s2 is a palindromic string and if reverse s1 is present in the hash-map then we get a pair (current word + reverse of s1).
- Repeat the above steps for all the strings in the array.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to check whether the string
// word is palindrome or not
bool ispalin(string word)
{
if (word.length() == 1
|| word.empty()) {
return true;
}
int l = 0;
int r = word.length() - 1;
// Iterate word
while (l <= r) {
if (word[l] != word[r]) {
return false;
}
l++;
r--;
}
return true;
}
// Function to find the palindromicPairs
vector<string>
palindromicPairs(vector<string>& words)
{
vector<string> output;
if (words.size() == 0
|| words.size() == 1) {
return output;
}
// Insert all the strings with
// their indices in the hash map
unordered_map<string, int> mp;
for (int i = 0; i < words.size(); i++) {
mp[words[i]] = i;
}
// Iterate over all the words
for (int i = 0; i < words.size(); i++) {
// If the word is empty then
// we simply pair it will all the
// words which are palindrome
// present in the array
// except the word itself
if (words[i].empty()) {
for (auto x : mp) {
if (x.second == i) {
continue;
}
if (ispalin(x.first)) {
output.push_back(x.first);
}
}
}
// Create all possible substrings
// s1 and s2
for (int j = 0;
j < words[i].length(); j++) {
string s1 = words[i].substr(0, j + 1);
string s2 = words[i].substr(j + 1);
// Case 1
// If s1 is palindrome and
// reverse of s2 is
// present in hashmap at
// index other than i
if (ispalin(s1)) {
reverse(s2.begin(),
s2.end());
string temp = s2;
if (mp.count(s2) == 1
&& mp[s2] != i) {
string ans = s2 + words[i];
output.push_back(ans);
}
s2 = temp;
}
// Case 2
// If s2 is palindrome and
// reverse of s1 is
// present in hashmap
// at index other than i
if (ispalin(s2)) {
string temp = s1;
reverse(s1.begin(),
s1.end());
if (mp.count(s1) == 1
&& mp[s1] != i) {
string ans = words[i] + s1;
output.push_back(ans);
}
s1 = temp;
}
}
}
// Return output
return output;
}
// Driver Code
int main()
{
vector<string> words;
// Given array of words
words = { "geekf", "geeks", "or",
"keeg", "abc", "ba" };
// Function call
vector<string> result
= palindromicPairs(words);
// Print the palindromic strings
// after combining them
for (auto x : result) {
cout << x << endl;
}
return 0;
}
Java
// Java program for the above approach
import java.util.*;
public class Main
{
// Function to check whether the string
// word is palindrome or not
static boolean ispalin(String word)
{
if (word.length() == 1
|| word.length() == 0) {
return true;
}
int l = 0;
int r = word.length() - 1;
// Iterate word
while (l <= r) {
if (word.charAt(l) != word.charAt(r)) {
return false;
}
l++;
r--;
}
return true;
}
// Function to find the palindromicPairs
static Vector<String> palindromicPairs(String[] words)
{
Vector<String> output = new Vector<String>();
if (words.length == 0 ||
words.length == 1)
{
return output;
}
// Insert all the strings with
// their indices in the hash map
HashMap<String, Integer> mp = new HashMap<>();
for (int i = 0; i < words.length; i++) {
mp.put(words[i], i);
}
// Iterate over all the words
for(int i = 0; i < words.length; i++)
{
// If the word is empty then
// we simply pair it will all the
// words which are palindrome
// present in the array
// except the word itself
if ((words[i]).length() == 0)
{
for(Map.Entry<String, Integer> key : mp.entrySet())
{
if (key.getValue() == i)
{
continue;
}
if (ispalin(key.getKey()))
{
output.add(key.getKey());
}
}
}
// Create all possible substrings
// s1 and s2
for(int j = 0; j < words[i].length(); j++)
{
String s1 = words[i].substring(0, j + 1);
String s2 = words[i].substring(j + 1);
// Case 1
// If s1 is palindrome and
// reverse of s2 is
// present in hashmap at
// index other than i
if (ispalin(s1))
{
StringBuffer arr = new StringBuffer(s2);
arr.reverse();
s2 = new String(arr);
String temp = s2;
if (mp.containsKey(s2) && mp.get(s2) != i)
{
String ans = s2 + words[i];
output.add(ans);
}
s2 = temp;
}
// Case 2
// If s2 is palindrome and
// reverse of s1 is
// present in hashmap
// at index other than i
if (ispalin(s2))
{
String temp = s1;
StringBuffer arr = new StringBuffer(s1);
arr.reverse();
s1 = new String(arr);
if (mp.containsKey(s1) && mp.get(s1) != i)
{
String ans = words[i] + s1;
output.add(ans);
}
s1 = temp;
}
}
}
// Return output
return output;
}
public static void main(String[] args) {
String[] words = { "geekf", "geeks", "or", "keeg", "abc", "ba" };
// Function call
Vector<String> result = palindromicPairs(words);
// Print the palindromic strings
// after combining them
for(String x : result)
System.out.println(x);
}
}
// This code is contributed by mukesh07.
Python3
# Python3 program for the above approach
# Function to check whether the string
# word is palindrome or not
def ispalin(word):
if (len(word) == 1 or len(word)):
return True
l = 0
r = len(word) - 1
# Iterate word
while (l <= r):
if (word[l] != word[r]):
return False
l+= 1
r-= 1
return True
# Function to find the palindromicPairs
def palindromicPairs(words):
output = []
if (len(words) == 0 or len(words) == 1):
return output
# Insert all the strings with
# their indices in the hash map
mp = {}
for i in range(len(words)):
mp[words[i]] = i
# Iterate over all the words
for i in range(len( words)):
# If the word is empty then
# we simply pair it will all the
# words which are palindrome
# present in the array
# except the word itself
if (len(words[i]) == 0):
for x in mp:
if (mp[x] == i):
continue
if (ispalin(x)):
output.append(x)
# Create all possible substrings
# s1 and s2
for j in range (len(words[i])):
s1 = words[i][0 : j + 1]
s2 = words[i][j + 1 : ]
# Case 1
# If s1 is palindrome and
# reverse of s2 is
# present in hashmap at
# index other than i
if (ispalin(s1)):
p = list(s2)
p.reverse()
s2 = ''.join(p)
temp = s2;
if (s2 in mp and mp[s2] != i):
ans = s2 + words[i]
output.append(ans)
s2 = temp
# Case 2
# If s2 is palindrome and
# reverse of s1 is
# present in hashmap
# at index other than i
if (ispalin(s2)):
temp = s1
p = list(s1)
p.reverse()
s1 = ''.join(p)
if (s1 in mp and mp[s1] != i):
ans = words[i] + s1
output.append(ans)
s1 = temp
# Return output
return output
# Driver Code
if __name__ == "__main__":
# Given array of words
words = [ "geekf", "geeks", "or",
"keeg", "abc", "ba" ]
# Function call
result = palindromicPairs(words);
# Print the palindromic strings
# after combining them
for x in result:
print(x)
# This code is contributed by chitranayal
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG {
// Function to check whether the string
// word is palindrome or not
static bool ispalin(string word)
{
if (word.Length == 1
|| word.Length == 0) {
return true;
}
int l = 0;
int r = word.Length - 1;
// Iterate word
while (l <= r) {
if (word[l] != word[r]) {
return false;
}
l++;
r--;
}
return true;
}
// Function to find the palindromicPairs
static List<string> palindromicPairs(string[] words)
{
List<string> output = new List<string>();
if (words.Length == 0 ||
words.Length == 1)
{
return output;
}
// Insert all the strings with
// their indices in the hash map
Dictionary<string, int> mp = new Dictionary<string, int>();
for (int i = 0; i < words.Length; i++) {
mp[words[i]] = i;
}
// Iterate over all the words
for(int i = 0; i < words.Length; i++)
{
// If the word is empty then
// we simply pair it will all the
// words which are palindrome
// present in the array
// except the word itself
if (words[i].Length == 0)
{
foreach(KeyValuePair<string, int> key in mp)
{
if (key.Value == i)
{
continue;
}
if (ispalin(key.Key))
{
output.Add(key.Key);
}
}
}
// Create all possible substrings
// s1 and s2
for(int j = 0; j < words[i].Length; j++)
{
string s1 = words[i].Substring(0, j + 1);
string s2 = words[i].Substring(j + 1);
// Case 1
// If s1 is palindrome and
// reverse of s2 is
// present in hashmap at
// index other than i
if (ispalin(s1))
{
char[] arr = s2.ToCharArray();
Array.Reverse(arr);
s2 = new string(arr);
string temp = s2;
if (mp.ContainsKey(s2) && mp[s2] != i)
{
string ans = s2 + words[i];
output.Add(ans);
}
s2 = temp;
}
// Case 2
// If s2 is palindrome and
// reverse of s1 is
// present in hashmap
// at index other than i
if (ispalin(s2))
{
string temp = s1;
char[] arr = s1.ToCharArray();
Array.Reverse(arr);
s1 = new string(arr);
if (mp.ContainsKey(s1) && mp[s1] != i)
{
string ans = words[i] + s1;
output.Add(ans);
}
s1 = temp;
}
}
}
// Return output
return output;
}
static void Main()
{
string[] words = { "geekf", "geeks", "or", "keeg", "abc", "ba" };
// Function call
List<string> result = palindromicPairs(words);
// Print the palindromic strings
// after combining them
foreach(string x in result) {
Console.WriteLine(x);
}
}
}
// This code is contributed by rameshtravel07.
JavaScript
<script>
// Javascript program for the above approach
// Function to check whether the string
// word is palindrome or not
function ispalin(word)
{
if (word.length == 1 ||
word.length == 0)
{
return true;
}
let l = 0;
let r = word.length - 1;
// Iterate word
while (l <= r)
{
if (word[l] != word[r])
{
return false;
}
l++;
r--;
}
return true;
}
// Function to find the palindromicPairs
function palindromicPairs(words)
{
let output = [];
if (words.length == 0 ||
words.length == 1)
{
return output;
}
// Insert all the strings with
// their indices in the hash map
let mp = new Map();
for(let i = 0; i < words.length; i++)
{
mp.set(words[i],i);
}
// Iterate over all the words
for(let i = 0; i < words.length; i++)
{
// If the word is empty then
// we simply pair it will all the
// words which are palindrome
// present in the array
// except the word itself
if (words[i].length == 0)
{
for(let [key, value] of mp.entries())
{
if (value == i)
{
continue;
}
if (ispalin(key))
{
output.push(key);
}
}
}
// Create all possible substrings
// s1 and s2
for(let j = 0; j < words[i].length; j++)
{
let s1 = words[i].substring(0, j + 1);
let s2 = words[i].substring(j + 1);
// Case 1
// If s1 is palindrome and
// reverse of s2 is
// present in hashmap at
// index other than i
if (ispalin(s1))
{
s2 = s2.split("").reverse().join("");
let temp = s2;
if (mp.has(s2) && mp.get(s2) != i)
{
let ans = s2 + words[i];
output.push(ans);
}
s2 = temp;
}
// Case 2
// If s2 is palindrome and
// reverse of s1 is
// present in hashmap
// at index other than i
if (ispalin(s2))
{
let temp = s1;
s1 = s1.split("").reverse().join("");
if (mp.has(s1) && mp.get(s1) != i)
{
let ans = words[i] + s1;
output.push(ans);
}
s1 = temp;
}
}
}
// Return output
return output;
}
// Driver Code
let words;
// Given array of words
words = [ "geekf", "geeks", "or",
"keeg", "abc", "ba" ];
// Function call
let result = palindromicPairs(words);
// Print the palindromic strings
// after combining them
for(let i = 0; i < result.length; i++)
{
document.write(result[i] + " <br>");
}
// This code is contributed by avanitrachhadiya2155
</script>
Output: geekfkeeg
geekskeeg
abcba
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
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
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
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
Find all Palindrome Strings in given Array of strings
Given an array of strings arr[] of size N where each string consists only of lowercase English letter. The task is to find all palindromic string in the array. Print -1 if no palindrome is present in the given array. Examples: Input: arr[] = {"abc", "car", "ada", "racecar", "cool"}Output: "ada", "ra
6 min read
Check if K palindromic strings can be formed from a given string
Given a string S of size N and an integer K, the task is to find whether the characters of the string can be arranged to make K palindromic strings simultaneously. Examples: Input: S = "annabelle", K = 2 Output: Yes Explanation: All characters of string S can be distributed into "elble" and "anna" w
7 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
Split string into three palindromic substrings with earliest possible cuts
Given string str, the task is to check if it is possible to split the given string S into three palindromic substrings or not. If multiple answers are possible, then print the one where the cuts are made the least indices. If no such possible partition exists, then print "-1". Examples: Input: str =
15+ min read
Count of Palindromic Strings possible by swapping of a pair of Characters
Given a palindromic string S, the task is to find the count of palindromic strings possible by swapping a pair of character at a time.Examples: Input: s = "abba" Output: 2 Explanation: 1st Swap: abba -> abba 2nd Swap: abba -> abba All other swaps will lead to a non-palindromic string. Therefor
4 min read
All distinct palindromic sub-strings of a given string
Given a string str of lowercase ASCII characters. The task is to find all the distinct continuous palindromic sub-strings which are present in the string str. Examples: Input: str = "abaaa"Output: [ "a", "aa", "aaa", "aba", "b" ]Explanation: All 5 distinct continuous palindromic sub-strings are list
15+ min read
Distinct palindromic sub-strings of the given string using Dynamic Programming
Given a string str of lowercase alphabets, the task is to find all distinct palindromic sub-strings of the given string. Examples: Input: str = "abaaa" Output: 5 Palindromic sub-strings are "a", "aa", "aaa", "aba" and "b" Input: str = "abcd" Output: 4 Approach: The solution to this problem has been
8 min read