Check if a palindromic string can be obtained by concatenating substrings split from same indices of two given strings

Given two strings A and B of length N, the task is to check if any of the two strings formed by splitting both the strings at any index i (0 ≤ i ≤ N – 1) and concatenating A[0, i] and B[i, N – 1] or A[i, N – 1] and B[0, i] respectively, form a palindromic string or not. If found to be true, print “Yes”. Otherwise, print “No”.

Examples:

Input: A = “x”, B = “y”
Output: Yes
Explanation:
Let the string be spitted at index 0 then, 
Split A from index 0: “”+”x” A[0, 0] = “” and A[1, 1] = “x”.
Split B from index 0: “”+”y” B[0, 0] = “” and B[1, 1] = “y”.
The concatenation of A[0, 0] and B[1, 1] is = “y” which is a palindromic string.

Input: A = “xbdef”, B = “xecab”
Output: No

Approach: The idea is to use the Two Pointer Technique and traverse the string over the range [0, N – 1] and check if the concatenation of substrings A[0, i – 1] and B[i, N – 1] or the concatenation of substrings A[i, N – 1] and B[0, i – 1] is a palindromic or not. If any of the concatenation is found to be palindromic then print “Yes” else print “No”.



Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if a string
// is palindrome or not
bool isPalindrome(string str)
{
  // Start and end of the
  // string
  int i = 0, j = str.size() - 1;
 
  // Iterate the string
  // until i > j
  while (i < j)
  {
    // If there is a mismatch
    if (str[i] != str[j])
      return false;
 
    // Increment first pointer
    // and decrement the other
    i++;
    j--;
  }
 
  // Given string is a
  // palindrome
  return true;
}
 
// Function two check if
// the strings can be
// combined to form a palindrome
void formPalindrome(string a,
                    string b, int n)
{
  // Initialize array of
  // characters
  char aa[n + 2];
  char bb[n + 2];
  for (int i = 0; i < n + 2; i++)
  {
    aa[i] = ' ';
    bb[i] = ' ';
  }
  // Stores character of string
  // in the character array
  for (int i = 1; i <= n; i++)
  {
    aa[i] = a[i - 1];
    bb[i] = b[i - 1];
  }
 
  bool ok = false;
 
  for (int i = 0; i <= n + 1; i++)
  {
    // Find left and right parts
    // of strings a and b
    string la = "";
    string ra = "";
    string lb = "";
    string rb = "";
 
    for (int j = 1; j <= i - 1; j++)
    {
      // Substring a[j...i-1]
      if (aa[j] == ' ')
        la += "";
      else
        la += aa[j];
 
      // Substring b[j...i-1]
      if (bb[j] == ' ')
        lb += "";
      else
        lb += bb[j];
    }
 
    for (int j = i; j <= n + 1; j++)
    {
      // Substring a[i...n]
      if (aa[j] == ' ')
        ra += "";
      else
        ra += aa[j];
 
      // Substring b[i...n]
      if (bb[j] == ' ')
        rb += "";
      else
        rb += bb[j];
    }
 
    // Check is left part of a +
    // right part of b or vice
    // versa is a palindrome
    if (isPalindrome(la + rb) ||
        isPalindrome(lb + ra))
    {
      ok = true;
      break;
    }
  }
 
  // Print the result
  if (ok)
    cout << ("Yes");
 
  // Otherwise
  else
    cout << ("No");
}
 
// Driver Code
int main()
{
  string A = "bdea";
  string B = "abbb";
  int N = 4;
  formPalindrome(A, B, N);
}
 
// This code is contributed by gauravrajput1

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
 
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to check if a string
    // is palindrome or not
    static boolean isPalindrome(String str)
    {
 
        // Start and end of the string
        int i = 0, j = str.length() - 1;
 
        // Iterate the string until i > j
        while (i < j) {
 
            // If there is a mismatch
            if (str.charAt(i)
                != str.charAt(j))
                return false;
 
            // Increment first pointer and
            // decrement the other
            i++;
            j--;
        }
 
        // Given string is a palindrome
        return true;
    }
 
    // Function two check if the strings can
    // be combined to form a palindrome
    static void formPalindrome(
        String a, String b, int n)
    {
        // Initialize array of characters
        char aa[] = new char[n + 2];
        char bb[] = new char[n + 2];
 
        Arrays.fill(aa, ' ');
        Arrays.fill(bb, ' ');
 
        // Stores character of string
        // in the character array
        for (int i = 1; i <= n; i++) {
            aa[i] = a.charAt(i - 1);
            bb[i] = b.charAt(i - 1);
        }
 
        boolean ok = false;
 
        for (int i = 0; i <= n + 1; i++) {
 
            // Find left and right parts
            // of strings a and b
            StringBuilder la
                = new StringBuilder();
            StringBuilder ra
                = new StringBuilder();
            StringBuilder lb
                = new StringBuilder();
            StringBuilder rb
                = new StringBuilder();
 
            for (int j = 1;
                 j <= i - 1; j++) {
 
                // Substring a[j...i-1]
                la.append((aa[j] == ' ')
                              ? ""
                              : aa[j]);
 
                // Substring b[j...i-1]
                lb.append((bb[j] == ' ')
                              ? ""
                              : bb[j]);
            }
 
            for (int j = i;
                 j <= n + 1; j++) {
 
                // Substring a[i...n]
                ra.append((aa[j] == ' ')
                              ? ""
                              : aa[j]);
 
                // Substring b[i...n]
                rb.append((bb[j] == ' ')
                              ? ""
                              : bb[j]);
            }
 
            // Check is left part of a +
            // right part of b or vice
            // versa is a palindrome
            if (isPalindrome(la.toString()
                             + rb.toString())
                || isPalindrome(lb.toString()
                                + ra.toString())) {
                ok = true;
                break;
            }
        }
 
        // Print the result
        if (ok)
            System.out.println("Yes");
 
        // Otherwise
        else
            System.out.println("No");
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String A = "bdea";
        String B = "abbb";
 
        int N = 4;
 
        formPalindrome(A, B, N);
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the
# above approach
 
# Function to check if
# a string is palindrome
# or not
def isPalindrome(st):
 
    # Start and end of
    # the string
    i = 0
    j = len(st) - 1
 
    # Iterate the string
    # until i > j
    while (i < j):
 
        # If there is a mismatch
        if (st[i] != st[j]):
            return False
 
        # Increment first pointer
        # and decrement the other
        i += 1
        j -= 1
 
    # Given string is a
    # palindrome
    return True
 
# Function two check if
# the strings can be
# combined to form a
# palindrome
def formPalindrome(a, b, n):
 
    # Initialize array of
    # characters
    aa = [' '] * (n + 2)
    bb = [' '] * (n + 2)
 
    # Stores character of string
    # in the character array
    for i in range(1, n + 1):
        aa[i] = a[i - 1]
        bb[i] = b[i - 1]
 
    ok = False
 
    for i in range(n + 2):
 
        # Find left and right parts
        # of strings a and b
        la = ""
        ra = ""
        lb = ""
        rb = ""
 
        for j in range(1, i):
 
            # Substring a[j...i-1]
            if (aa[j] == ' '):
                la += ""
            else:
                la += aa[j]
 
            # Substring b[j...i-1]
            if (bb[j] == ' '):
                lb += ""
            else:
                lb += bb[j]
 
        for j in range(i, n + 2):
 
            # Substring a[i...n]
            if (aa[j] == ' '):
                ra += ""
            else:
                ra += aa[j]
 
            # Substring b[i...n]
            if (bb[j] == ' '):
                rb += ""
            else:
                rb += bb[j]
 
        # Check is left part of a +
        # right part of b or vice
        # versa is a palindrome
        if (isPalindrome(str(la) +
                         str(rb))
            or isPalindrome(str(lb) +
                            str(ra))):
            ok = True
            break
 
    # Print the result
    if (ok):
        print("Yes")
 
    # Otherwise
    else:
        print("No")
 
# Driver Code
if __name__ == "__main__":
 
    A = "bdea"
    B = "abbb"
    N = 4
    formPalindrome(A, B, N)
 
# This code is contributed by Chitranayal

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the
// above approach
using System;
using System.Text;
class GFG{
 
// Function to check if a string
// is palindrome or not
static bool isPalindrome(String str)
{
  // Start and end of the string
  int i = 0, j = str.Length - 1;
 
  // Iterate the string
  // until i > j
  while (i < j)
  {
    // If there is a mismatch
    if (str[i] != str[j])
      return false;
 
    // Increment first pointer
    // and decrement the other
    i++;
    j--;
  }
 
  // Given string is
  // a palindrome
  return true;
}
 
// Function two check if the strings can
// be combined to form a palindrome
static void formPalindrome(String a,
                           String b, int n)
{
  // Initialize array of
  // characters
  char []aa = new char[n + 2];
  char []bb = new char[n + 2];
 
  for(int i = 0; i < n + 2; i++)
  {
    aa[i] = ' ';
    bb[i] = ' ';
  }
 
  // Stores character of string
  // in the character array
  for (int i = 1; i <= n; i++)
  {
    aa[i] = a[i-1];
    bb[i] = b[i-1];
  }
 
  bool ok = false;
 
  for (int i = 0;
           i <= n + 1; i++)
  {
    // Find left and right parts
    // of strings a and b
    StringBuilder la =
          new StringBuilder();
    StringBuilder ra =
          new StringBuilder();
    StringBuilder lb =
          new StringBuilder();
    StringBuilder rb =
          new StringBuilder();
 
    for (int j = 1;
             j <= i - 1; j++)
    {
      // Substring a[j...i-1]
      la.Append((aa[j] == ' ') ?
                ' ' : aa[j]);
 
      // Substring b[j...i-1]
      lb.Append((bb[j] == ' ') ?
                ' ' : bb[j]);
    }
 
    for (int j = i;
             j <= n + 1; j++)
    {
      // Substring a[i...n]
      ra.Append((aa[j] == ' ') ?
                ' ' : aa[j]);
 
      // Substring b[i...n]
      rb.Append((bb[j] == ' ') ?
                ' ' : bb[j]);
    }
 
    // Check is left part of a +
    // right part of b or vice
    // versa is a palindrome
    if (isPalindrome(la.ToString() +
                     rb.ToString()) ||
        isPalindrome(lb.ToString() +
                     ra.ToString()))
    {
      ok = true;
      break;
    }
  }
 
  // Print the result
  if (!ok)
    Console.WriteLine("Yes");
 
  // Otherwise
  else
    Console.WriteLine("No");
}
 
// Driver Code
public static void Main(String[] args)
{
  String A = "bdea";
  String B = "abbb";
  int N = 4;
  formPalindrome(A, B, N);
}
}
 
// This code is contributed by 29AjayKumar

chevron_right


Output

Yes




Time Complexity: O(N2) where N is the lengths of the given strings.
Auxiliary Space: O(N)

Alternate Python Approach(Two pointers +Slicing):

This approach follows the following path:

  1. Define the function check
  2. Take two pointers i,j at 0, n-1 position respectively
  3. If the first character of a and second character of b does not match we break (since we are searching for the palindrome)
  4. If matches we simply increment the pointer
  5. We would concatenate the form a[i:j+1] of the first string and b[i:j+1] of the second string and check for the condition of palindrome
  6. If yes we return True

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to implement
// the above approach
#include<bits/stdc++.h>
using namespace std;
 
string rev(string str)
{
  int st = 0;
  int ed = str.length() - 1;
  string s = str;
   
  while(st < ed)
  {
    swap(s[st],
         s[ed]);
    st++;
    ed--;
  }
  return s;
}
 
 
bool check(string a,
           string b, int n)
{
  int i = 0;
  int j = n - 1;
 
  // iterate through the
  // length if we could
  // find a[i]==b[j] we could
  // increment I and decrement j
  while(i < n)
  {
    if(a[i] != b[j])
      break;
 
    // else we could just break
    // the loop as its not a
    // palindrome type sequence
    i += 1;
    j -= 1;
 
    // we could concatenate the
    // a's left part +b's right
    // part in a variable a and
    // a's right part+b's left
    // in the variable b
    string xa = a.substr(i, j + 1 - i);
    string xb = b.substr(i, j + 1 - i);
 
    // we would check for the
    // palindrome condition if
    // yes we print True else False
    if((xa == rev(xa)) or
       (xb == rev(xb)))
      return true;
  }
  return false;
}
     
// Driver code
int main()
{
  string a = "xbdef";
  string b = "cabex";
  if (check(a, b,
            a.length()) == true or
      check(b, a,
            a.length()) == true)
    cout << "True";
  else
    cout << "False";
}
 
// This code is contributed by Surendra_Gangwar

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

def check(a, b, n):
    i, j = 0, n - 1
     
    # iterate through the length if
    # we could find a[i]==b[j] we could
    # increment I and decrement j
    while(i < n):
        if(a[i] != b[j]):
             
            # else we could just break
            # the loop as its not a palindrome
            # type sequence
            break 
             
        i += 1
        j -= 1
         
        # we could concatenate the a's left part
        # +b's right part in a variable a and  a's
        # right part+b's left in the variable b
        xa = a[i:j+1]
        xb = b[i:j+1]
         
        # we would check for the palindrome condition
        # if yes we print True else False
        if(xa == xa[::-1] or xb == xb[::-1]):
            return True
 
 
a = "xbdef"
b = "cabex"
if check(a, b, len(a)) == True or check(b, a, len(a)) == True:
    print(True)
else:
    print(False)
 
     
# CODE CONTRIBUTED BY SAIKUMAR KUDIKALA

chevron_right


Output:

False

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:

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.