Open In App

Check if a Palindromic String can be formed by concatenating Substrings of two given Strings

Given two strings str1 and str2, the task is to check if it is possible to form a Palindromic String by concatenation of two substrings of str1 and str2.

Examples:

Input: str1 = “abcd”, str2 = “acba”
Output: Yes
Explanation:
There are five possible cases where concatenation of two substrings from str1 and str2 gives palindromic string:
“ab” + “a” = “aba”
“ab” + “ba” = “abba”
“bc” + “cb” = “bccb”
“bc” + “b” = “bcb”
“cd” + “c” = “cdc”

Input: str1 = “pqrs”, str2 = “abcd”
Output: No
Explanation:
There is no possible concatenation of sub-strings from given strings which gives palindromic string.

Naive Approach:
The simplest approach to solve the problem is to generate every possible substring of str1 and str2 and combine them to generate all possible concatenations. For each concatenation, check if it is palindromic or not. If found to be true, print “Yes”. Otherwise, print “No”.
Time Complexity: O(N2* M2 * (N+M)), where N and M are the lengths of str1 and str2 respectively.
Auxiliary Space: O(1)

Efficient Approach:
To optimize the above approach, the following observation needs to be made:

If the given strings possess at least one common character, then they will always form a palindromic string on concatenation of the common character from both the strings. 
Illustration:
str1 = “abc”, str2 = “fad” 
Since ‘a’ is common in both strings, a palindromic string “aa” can be obtained. 

Follow the steps below to solve the problem:

Below is the implementation of the above approach:




// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if a palindromic
// string can be formed from the
// substring of given strings
bool check(string str1, string str2)
{
    // Boolean array to mark
    // presence of characters
    vector<bool> mark(26, false);
 
    int n = str1.size(),
        m = str2.size();
 
    for (int i = 0; i < n; i++) {
 
        mark[str1[i] - 'a'] = true;
    }
 
    // Check if any of the character
    // of str2 is already marked
    for (int i = 0; i < m; i++) {
 
        // If a common character
        // is found
        if (mark[str2[i] - 'a'])
            return true;
    }
 
    // If no common character
    // is found
    return false;
}
 
// Driver Code
int main()
{
 
    string str1 = "abca",
        str2 = "efad";
 
    if (check(str1, str2))
        cout << "Yes";
    else
        cout << "No";
 
    return 0;
}




// Java program to implement
// the above approach
import java.util.Arrays;
 
class GFG{
     
// Function to check if a palindromic
// string can be formed from the
// substring of given strings
public static boolean check(String str1,
                            String str2)
{
     
    // Boolean array to mark
    // presence of characters
    boolean[] mark = new boolean[26];
    Arrays.fill(mark, false);
     
    int n = str1.length(),
        m = str2.length();
 
    for(int i = 0; i < n; i++)
    {
        mark[str1.charAt(i) - 'a'] = true;
    }
 
    // Check if any of the character
    // of str2 is already marked
    for(int i = 0; i < m; i++)
    {
 
        // If a common character
        // is found
        if (mark[str2.charAt(i) - 'a'])
            return true;
    }
 
    // If no common character
    // is found
    return false;
}
 
// Driver code
public static void main(String[] args)
{
    String str1 = "abca",
    str2 = "efad";
 
    if (check(str1, str2))
        System.out.println("Yes");
    else
        System.out.println("No");
}
}
 
// This code is contributed by divyeshrabadiya07




# Python3 program to implement
# the above approach
     
# Function to check if a palindromic
# string can be formed from the
# substring of given strings
def check(str1, str2):
     
    # Boolean array to mark
    # presence of characters
    mark = [False for i in range(26)]
     
    n = len(str1)
    m = len(str2)
     
    for i in range(n):
        mark[ord(str1[i]) - ord('a')] = True
     
    # Check if any of the character
    # of str2 is already marked
    for i in range(m):
         
        # If a common character
        # is found
        if (mark[ord(str2[i]) - ord('a')]):
            return True;
 
    # If no common character
    # is found
    return False
     
# Driver code
if __name__=="__main__":
     
    str1 = "abca"
    str2 = "efad"
 
    if (check(str1, str2)):
        print("Yes");
    else:
        print("No");
 
# This code is contributed by rutvik_56




// C# program to implement
// the above approach
using System;
 
class GFG{
     
// Function to check if a palindromic
// string can be formed from the
// substring of given strings
public static bool check(String str1,
                        String str2)
{
     
    // Boolean array to mark
    // presence of characters
    bool[] mark = new bool[26];
     
    int n = str1.Length,
        m = str2.Length;
 
    for(int i = 0; i < n; i++)
    {
        mark[str1[i] - 'a'] = true;
    }
 
    // Check if any of the character
    // of str2 is already marked
    for(int i = 0; i < m; i++)
    {
 
        // If a common character
        // is found
        if (mark[str2[i] - 'a'])
            return true;
    }
 
    // If no common character
    // is found
    return false;
}
 
// Driver code
public static void Main(String[] args)
{
    String str1 = "abca",
    str2 = "efad";
 
    if (check(str1, str2))
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
}
}
 
// This code is contributed by amal kumar choubey




<script>
 
// Javascript Program to implement
// the above approach
 
// Function to check if a palindromic
// string can be formed from the
// substring of given strings
function check(str1, str2)
{
    // Boolean array to mark
    // presence of characters
    var mark = Array(26).fill(false);
 
    var n = str1.length,
        m = str2.length;
 
    for (var i = 0; i < n; i++) {
 
        mark[str1[i] - 'a'] = true;
    }
 
    // Check if any of the character
    // of str2 is already marked
    for (var i = 0; i < m; i++) {
 
        // If a common character
        // is found
        if (mark[str2[i] - 'a'])
            return true;
    }
 
    // If no common character
    // is found
    return false;
}
 
// Driver Code
var str1 = "abca",
    str2 = "efad";
if (check(str1, str2))
    document.write( "Yes");
else
    document.write( "No");
 
// This code is contributed by noob2000.
</script>

Output: 
Yes

Time Complexity: O(max(N, M)) where N and M are the lengths of str1 and str2 respectively. As, we are traversing both of the strings.
Auxiliary Space: O(1), as we are using any extra space.
 


Article Tags :