Check if a palindromic string can be obtained by concatenating substrings split from same indices of two given strings
Last Updated :
05 Apr, 2023
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 splitted 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++
#include <bits/stdc++.h>
using namespace std;
bool isPalindrome(string str)
{
int i = 0, j = str.size() - 1;
while (i < j)
{
if (str[i] != str[j])
return false ;
i++;
j--;
}
return true ;
}
void formPalindrome(string a,
string b, int n)
{
char aa[n + 2];
char bb[n + 2];
for ( int i = 0; i < n + 2; i++)
{
aa[i] = ' ' ;
bb[i] = ' ' ;
}
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++)
{
string la = "" ;
string ra = "" ;
string lb = "" ;
string rb = "" ;
for ( int j = 1; j <= i - 1; j++)
{
if (aa[j] == ' ' )
la += "" ;
else
la += aa[j];
if (bb[j] == ' ' )
lb += "" ;
else
lb += bb[j];
}
for ( int j = i; j <= n + 1; j++)
{
if (aa[j] == ' ' )
ra += "" ;
else
ra += aa[j];
if (bb[j] == ' ' )
rb += "" ;
else
rb += bb[j];
}
if (isPalindrome(la + rb) ||
isPalindrome(lb + ra))
{
ok = true ;
break ;
}
}
if (ok)
cout << ( "Yes" );
else
cout << ( "No" );
}
int main()
{
string A = "bdea" ;
string B = "abbb" ;
int N = 4;
formPalindrome(A, B, N);
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static boolean isPalindrome(String str)
{
int i = 0 , j = str.length() - 1 ;
while (i < j) {
if (str.charAt(i)
!= str.charAt(j))
return false ;
i++;
j--;
}
return true ;
}
static void formPalindrome(
String a, String b, int n)
{
char aa[] = new char [n + 2 ];
char bb[] = new char [n + 2 ];
Arrays.fill(aa, ' ' );
Arrays.fill(bb, ' ' );
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++) {
StringBuilder la
= new StringBuilder();
StringBuilder ra
= new StringBuilder();
StringBuilder lb
= new StringBuilder();
StringBuilder rb
= new StringBuilder();
for ( int j = 1 ;
j <= i - 1 ; j++) {
la.append((aa[j] == ' ' )
? ""
: aa[j]);
lb.append((bb[j] == ' ' )
? ""
: bb[j]);
}
for ( int j = i;
j <= n + 1 ; j++) {
ra.append((aa[j] == ' ' )
? ""
: aa[j]);
rb.append((bb[j] == ' ' )
? ""
: bb[j]);
}
if (isPalindrome(la.toString()
+ rb.toString())
|| isPalindrome(lb.toString()
+ ra.toString())) {
ok = true ;
break ;
}
}
if (ok)
System.out.println( "Yes" );
else
System.out.println( "No" );
}
public static void main(String[] args)
{
String A = "bdea" ;
String B = "abbb" ;
int N = 4 ;
formPalindrome(A, B, N);
}
}
|
Python3
def isPalindrome(st):
i = 0
j = len (st) - 1
while (i < j):
if (st[i] ! = st[j]):
return False
i + = 1
j - = 1
return True
def formPalindrome(a, b, n):
aa = [ ' ' ] * (n + 2 )
bb = [ ' ' ] * (n + 2 )
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 ):
la = ""
ra = ""
lb = ""
rb = ""
for j in range ( 1 , i):
if (aa[j] = = ' ' ):
la + = ""
else :
la + = aa[j]
if (bb[j] = = ' ' ):
lb + = ""
else :
lb + = bb[j]
for j in range (i, n + 2 ):
if (aa[j] = = ' ' ):
ra + = ""
else :
ra + = aa[j]
if (bb[j] = = ' ' ):
rb + = ""
else :
rb + = bb[j]
if (isPalindrome( str (la) +
str (rb))
or isPalindrome( str (lb) +
str (ra))):
ok = True
break
if (ok):
print ( "Yes" )
else :
print ( "No" )
if __name__ = = "__main__" :
A = "bdea"
B = "abbb"
N = 4
formPalindrome(A, B, N)
|
C#
using System;
using System.Text;
class GFG{
static bool isPalindrome(String str)
{
int i = 0, j = str.Length - 1;
while (i < j)
{
if (str[i] != str[j])
return false ;
i++;
j--;
}
return true ;
}
static void formPalindrome(String a,
String b, int n)
{
char []aa = new char [n + 2];
char []bb = new char [n + 2];
for ( int i = 0; i < n + 2; i++)
{
aa[i] = ' ' ;
bb[i] = ' ' ;
}
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++)
{
StringBuilder la =
new StringBuilder();
StringBuilder ra =
new StringBuilder();
StringBuilder lb =
new StringBuilder();
StringBuilder rb =
new StringBuilder();
for ( int j = 1;
j <= i - 1; j++)
{
la.Append((aa[j] == ' ' ) ?
' ' : aa[j]);
lb.Append((bb[j] == ' ' ) ?
' ' : bb[j]);
}
for ( int j = i;
j <= n + 1; j++)
{
ra.Append((aa[j] == ' ' ) ?
' ' : aa[j]);
rb.Append((bb[j] == ' ' ) ?
' ' : bb[j]);
}
if (isPalindrome(la.ToString() +
rb.ToString()) ||
isPalindrome(lb.ToString() +
ra.ToString()))
{
ok = true ;
break ;
}
}
if (!ok)
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
public static void Main(String[] args)
{
String A = "bdea" ;
String B = "abbb" ;
int N = 4;
formPalindrome(A, B, N);
}
}
|
Javascript
<script>
function isPalindrome(str)
{
var i = 0, j = str.length - 1;
while (i < j)
{
if (str[i] != str[j])
return false ;
i++;
j--;
}
return true ;
}
function formPalindrome( a, b, n)
{
var aa= new Array(n + 2);
var bb= new Array(n + 2);
for ( var i = 0; i < n + 2; i++)
{
aa[i] = ' ' ;
bb[i] = ' ' ;
}
for ( var i = 1; i <= n; i++)
{
aa[i] = a[i - 1];
bb[i] = b[i - 1];
}
var ok = Boolean( false );
for ( var i = 0; i <= n + 1; i++)
{
var la = "" ;
var ra = "" ;
var lb = "" ;
var rb = "" ;
for ( var j = 1; j <= i - 1; j++)
{
if (aa[j] == ' ' )
la += "" ;
else
la += aa[j];
if (bb[j] == ' ' )
lb += "" ;
else
lb += bb[j];
}
for ( var j = i; j <= n + 1; j++)
{
if (aa[j] == ' ' )
ra += "" ;
else
ra += aa[j];
if (bb[j] == ' ' )
rb += "" ;
else
rb += bb[j];
}
if (isPalindrome(la + rb) || isPalindrome(lb + ra))
{
ok = true ;
break ;
}
}
if (ok)
document.write ( "Yes" );
else
document.write ( "No" );
}
var A = "bdea" ;
var B = "abbb" ;
var N = 4;
formPalindrome(A, B, N);
</script>
|
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:
- Define the function check
- Take two pointers i,j at 0, n-1 position respectively
- If the first character of a and second character of b does not match we break (since we are searching for the palindrome)
- If matches we simply increment the pointer
- 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
- If yes we return True
C++
#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;
while (i < n)
{
if (a[i] != b[j])
break ;
i += 1;
j -= 1;
string xa = a.substr(i, j + 1 - i);
string xb = b.substr(i, j + 1 - i);
if ((xa == rev(xa)) or
(xb == rev(xb)))
return true ;
}
return false ;
}
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" ;
}
|
Java
import java.util.*;
import java.io.*;
class GFG{
public static String rev(String str)
{
int st = 0 ;
int ed = str.length() - 1 ;
char [] s = str.toCharArray();
while (st < ed)
{
char temp = s[st];
s[st] = s[ed];
s[ed] = temp;
st++;
ed--;
}
return (s.toString());
}
public static boolean check(String a,
String b, int n)
{
int i = 0 ;
int j = n - 1 ;
while (i < n)
{
if (a.charAt(i) != b.charAt(j))
break ;
i += 1 ;
j -= 1 ;
String xa = a.substring(i, j + 1 );
String xb = b.substring(i, j + 1 );
StringBuffer XA = new StringBuffer(xa);
XA.reverse();
StringBuffer XB = new StringBuffer(xb);
XB.reverse();
if (xa == XA.toString() ||
xb == XB.toString())
{
return true ;
}
}
return false ;
}
public static void main(String[] args)
{
String a = "xbdef" ;
String b = "cabex" ;
if (check(a, b, a.length()) ||
check(b, a, a.length()))
System.out.println( "True" );
else
System.out.println( "False" );
}
}
|
Python3
def check(a, b, n):
i, j = 0 , n - 1
while (i < n):
if (a[i] ! = b[j]):
break
i + = 1
j - = 1
xa = a[i:j + 1 ]
xb = b[i:j + 1 ]
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 )
|
C#
using System;
class GFG {
static string rev( string str)
{
int st = 0;
int ed = str.Length - 1;
char [] s = str.ToCharArray();
while (st < ed)
{
char temp = s[st];
s[st] = s[ed];
s[ed] = temp;
st++;
ed--;
}
return new string (s);
}
static bool check( string a,
string b, int n)
{
int i = 0;
int j = n - 1;
while (i < n)
{
if (a[i] != b[j])
break ;
i += 1;
j -= 1;
string xa = a.Substring(i, j + 1 - i);
string xb = b.Substring(i, j + 1 - i);
char [] XA = xa.ToCharArray();
Array.Reverse(XA);
char [] XB = xb.ToCharArray();
Array.Reverse(XB);
if ( string .Compare(xa, new string (XA)) == 0 ||
string .Compare(xb, new string (XB)) == 0)
return true ;
}
return false ;
}
static void Main()
{
string a = "xbdef" ;
string b = "cabex" ;
if (check(a, b, a.Length) || check(b, a, a.Length))
Console.WriteLine( "True" );
else
Console.WriteLine( "False" );
}
}
|
Javascript
<script>
function rev(str) {
var st = 0;
var ed = str.length - 1;
var s = str.split( "" );
while (st < ed) {
var temp = s[st];
s[st] = s[ed];
s[ed] = temp;
st++;
ed--;
}
return s.join();
}
function check(a, b, n) {
var i = 0;
var j = n - 1;
while (i < n) {
if (a[i] !== b[j]) break ;
i += 1;
j -= 1;
var xa = a.substring(i, j + 1 - i);
var xb = b.substring(i, j + 1 - i);
var XA = xa.split( "" );
XA.sort().reverse();
var XB = xb.split( "" );
XB.sort().reverse();
if (xa === XA.join( "" ) || xb === XB.join( "" )) return true ;
}
return false ;
}
var a = "xbdef" ;
var b = "cabex" ;
if (check(a, b, a.length) || check(b, a, a.length))
document.write( "True" );
else document.write( "False" );
</script>
|
Time Complexity : O( | a |*| a+b |) ,where | a | is size of string a and | a+b | is size of string (a+b)
Space Complexity : O( | a+b |)
Another Approach:
The two-pointer technique is used to solve this problem. Traverse the string over its length [0, n-1]. Check if the concatenation of the substrings a [0, i-1] and b [i, n-1] or b [0, i-1] and a [i, n-1], (where i is any index) is a palindromic string or not. If it is a palindromic string, return true else return false.
Below is the implementation of this approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isPalindrome(string s){
int i=0,j=s.size()-1;
while (i<=j){
if (s[i]!=s[j]){
return false ;
}
i++;
j--;
}
return true ;
}
bool checkStrings(string &a, string &b, int n){
for ( int i=0;i<n;i++){
if ((isPalindrome(a.substr(0,i)+b.substr(i))) || (isPalindrome(b.substr(0,i)+a.substr(i))) ){
return true ;
}
}
return false ;
}
int main() {
string a = "xyzdef" ;
string b = "rstzyx" ;
int n = 6;
if (checkStrings(a,b,n))
cout<< "true" ;
else
cout<< "false" ;
return 0;
}
|
Java
import java.util.*;
public class Main
{
public static boolean isPalindrome(String s)
{
int i = 0 , j = s.length() - 1 ;
while (i <= j) {
if (s.charAt(i) != s.charAt(j)) {
return false ;
}
i++;
j--;
}
return true ;
}
public static boolean checkStrings(String a, String b,
int n)
{
for ( int i = 0 ; i < n; i++) {
if ((isPalindrome(a.substring( 0 , i)
+ b.substring(i)))
|| (isPalindrome(b.substring( 0 , i)
+ a.substring(i)))) {
return true ;
}
}
return false ;
}
public static void main(String[] args)
{
String a = "xyzdef" ;
String b = "rstzyx" ;
int n = 6 ;
if (checkStrings(a, b, n)) {
System.out.println( "true" );
}
else {
System.out.println( "false" );
}
}
}
|
C#
using System;
namespace PalindromeCheck {
class Program {
static bool IsPalindrome( string s)
{
int i = 0, j = s.Length - 1;
while (i <= j) {
if (s[i] != s[j]) {
return false ;
}
i++;
j--;
}
return true ;
}
static bool CheckStrings( ref string a, ref string b,
int n)
{
for ( int i = 0; i < n; i++) {
if ((IsPalindrome(a.Substring(0, i)
+ b.Substring(i)))
|| (IsPalindrome(b.Substring(0, i)
+ a.Substring(i)))) {
return true ;
}
}
return false ;
}
static void Main( string [] args)
{
string a = "xyzdef" ;
string b = "rstzyx" ;
int n = 6;
if (CheckStrings( ref a, ref b, n))
Console.WriteLine( "true" );
else
Console.WriteLine( "false" );
Console.ReadKey();
}
}
}
|
Python3
def isPalindrome(s):
i = 0
j = len (s) - 1
while i < = j:
if s[i] ! = s[j]:
return False
i + = 1
j - = 1
return True
def checkStrings(a, b, n):
for i in range (n):
if (isPalindrome(a[:i] + b[i:])) or (isPalindrome(b[:i] + a[i:])):
return True
return False
a = "xyzdef"
b = "rstzyx"
n = 6
if checkStrings(a, b, n):
print ( "true" )
else :
print ( "false" )
|
Javascript
function isPalindrome(s) {
let i = 0,
j = s.length - 1;
while (i <= j) {
if (s[i] != s[j]) {
return false ;
}
i++;
j--;
}
return true ;
}
function checkStrings(a, b, n) {
for (let i = 0; i < n; i++) {
if ((isPalindrome(a.substr(0, i) + b.substr(i))) || (isPalindrome(b.substr(0, i) + a.substr(i)))) {
return true ;
}
}
return false ;
}
let a = "xyzdef" ;
let b = "rstzyx" ;
let n = 6;
if (checkStrings(a, b, n))
console.log( "true" );
else
console.log( "false" );
|
Time Complexity: O(n)
Space Complexity: O(1)
Similar Reads
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: YesExplanation:There are five possible cases where concatenation of two substrings from str1
6 min read
Check if concatenation of splitted substrings of two given strings forms a palindrome or not
Given two strings a and b of the same length, the task is to check if splitting both the strings and concatenating their opposite substrings, i.e. concatenating the left substring of a with right substring of b or concatenating the left substring of b with right substring of a, forms a palindrome or
8 min read
Check if substrings from three given strings can be concatenated to form a palindrome
https://write.geeksforgeeks.org/internshipGiven three strings S1, S2, and S3 of lengths L, M, and N respectively, the task is to check if it is possible to choose some non-empty substrings from S1, S2, and S3 such that their concatenation is a palindrome. If found to be true, print "YES". Otherwise,
5 min read
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 Appr
15+ min read
Count of palindromes that can be obtained by concatenating equal length prefix and substrings
Prerequisites: Z-algorithm Given a string S, the task is to find the maximum number of palindromes that can be formed after performing the given steps: Choose a non-empty prefix P and a non-empty substring T of equal length.Reverse either P or T and concatenate them. Note: P and T can be overlapping
6 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
Rearrange characters of a string to make it a concatenation of palindromic substrings
Given a string S consisting of lowercase alphabets, the task is to check whether the given string can be rearranged such that the string can be split into non-overlapping palindromic substrings of at least length 2. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: S = "
6 min read
Check if a string can be split into even length palindromic substrings
Given a string str, the task is to check if it is possible to split the given string into even length palindromic substrings. Examples: Input: str = "abbacc" Output: Yes Explanation: Strings "abba" and "cc" are the even length palindromic substrings.Input: str = "abcde" Output: No Explanation: No ev
6 min read
Check if a string contains a palindromic sub-string of even length
S is string containing only lowercase English alphabets. We need to find if there exists at least one palindromic sub-string whose length is even. Examples: Input : aassssOutput : YESInput : gfgOutput : NOApproach: Approach to solve this problem is to check all even-length substrings of the given st
8 min read
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