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
  • Practice Searching Algorithms
  • MCQs on Searching Algorithms
  • Tutorial on Searching Algorithms
  • Linear Search
  • Binary Search
  • Ternary Search
  • Jump Search
  • Sentinel Linear Search
  • Interpolation Search
  • Exponential Search
  • Fibonacci Search
  • Ubiquitous Binary Search
  • Linear Search Vs Binary Search
  • Interpolation Search Vs Binary Search
  • Binary Search Vs Ternary Search
  • Sentinel Linear Search Vs Linear Search
Open In App
Next Article:
Count pair of strings whose concatenation of substrings form a palindrome
Next article icon

Check if concatenation of splitted substrings of two given strings forms a palindrome or not

Last Updated : 08 Feb, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 not. If found to be true print “Yes”. Otherwise, print “No”.

Note: One of the splitted substrings can be empty.

Examples:

Input: a = “x”, b = “y”
Output: Yes
Explanation:
Split both the strings at index 0. 
Left substring of a (aLeft) = ” “, Right substring of a (aRight) = “x”
Left substring of b (bLeft) = ” “, Right substring of b (bRight) = “y”
Since aLeft + bRight = ” ” + “y” = “y”, which is a palindrome as well as bLeft + aRight= ” ” + “x” = “x” is also a palindrome, print Yes.

Input: a = “ulacfd”, b = “jizalu”
Output: True
Explanation: 
Split both the strings at index 3:
Left substring of a (aLeft) = “ula”, Right substring of a (aRight) = “cfd”
, Left substring of b (bLeft) = “jiz”, Right substring of b (bRight) = “alu”
Since aleft + bright = “ula” + “alu” = “ulaalu”, which is a palindrome, print Yes.

Approach: The idea is to use Two Pointer technique to solve this problem. Follow the steps below to solve the problem:

  1. Place a pointer i at 0th index of a and “j” at the last index of b.
  2. Iterate over the characters of the string and check if a[i] == b[j], then increment i and decrement j.
  3. Otherwise, just break the loop as its not a palindrome type sequence.
  4. Concatenate aLeft and bRight in a string variable xa and aRight and bLeft in another string variable xb.
  5. Check if either of the two strings is a palindrome or not. If found to be true, print “Yes”. Otherwise, print “No”.

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 if concatenating
// opposite substrings after splitting
// two given strings forms a palindrome
// or not
bool checkSplitting(string a, string b)
{
     
    // Length of the string
    int len = a.length();
    int i = 0, j = len - 1;
     
    // Iterate through the strings
    while (i < len)
    {
         
        // If not a palindrome sequence
        if (a[i] != b[j])
        {
            break;
        }
        i += 1;
        j -= 1;
 
        // Concatenate left substring of a
        // and right substring of b in xa
        // Concatenate right substring of a
        // and left substring of b in xb
        string xa = a.substr(i, j + 1);
        string xb = b.substr(i, j + 1);
 
        // Check if either of the two concatenated
        // strings is a palindrome or not
        if (xa == string(xa.rbegin(), xa.rend()) ||
            xb == string(xb.rbegin(), xb.rend()))
            return true;
    }
}
 
// Function to check if concatenation of splitted
// substrings of two given strings forms a palindrome
void isSplitPossible(string a, string b)
{
    if (checkSplitting(a, b) == true)
    {
        cout << "Yes";
    }
    else if (checkSplitting(b, a) == true)
    {
        cout << "Yes";
    }
    else
    {
        cout << "No";
    }
}
 
// Driver Code
int main()
{
    string a = "ulacfd", b = "jizalu";
 
    // Function Call
    isSplitPossible(a, b);
     
    return 0;
}
 
// This code is contributed by pushpendrayadav1057
 
 

Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to check if concatenating
// opposite subStrings after splitting
// two given Strings forms a palindrome
// or not
static boolean checkSplitting(String a, String b)
{
     
    // Length of the String
    int len = a.length();
    int i = 0, j = len - 1;
     
    // Iterate through the Strings
    while (i < len)
    {
         
        // If not a palindrome sequence
        if (a.charAt(i) != b.charAt(j))
        {
            break;
        }
        i += 1;
        j -= 1;
 
        // Concatenate left subString of a
        // and right subString of b in xa
        // Concatenate right subString of a
        // and left subString of b in xb
        String xa = a.substring(i, j + 1);
        String xb = b.substring(i, j + 1);
 
        // Check if either of the two concatenated
        // Strings is a palindrome or not
        if (xa.equals(reverse(xa))||xb.equals(reverse(xb)))
            return true;
    }
    return false;
}
 
// Function to check if concatenation of splitted
// subStrings of two given Strings forms a palindrome
static void isSplitPossible(String a, String b)
{
    if (checkSplitting(a, b) == true)
    {
        System.out.print("Yes");
    }
    else if (checkSplitting(b, a) == true)
    {
        System.out.print("Yes");
    }
    else
    {
        System.out.print("No");
    }
}
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);
}
   
// Driver Code
public static void main(String[] args)
{
    String a = "ulacfd", b = "jizalu";
 
    // Function Call
    isSplitPossible(a, b);   
}
}
 
// This code is contributed by 29AjayKumar
 
 

Python3




# Python3 program for the above approach
 
# Function to check if concatenating
# opposite substrings after splitting
# two given strings forms a palindrome or not
def checkSplitting(a, b, n):
    i, j = 0, n - 1
 
    # Iterate through the strings
    while(i < n):
 
         
        # If not a palindrome sequence
        if(a[i] != b[j]):
            break
        i += 1
        j -= 1
 
        # Concatenate left substring of a
        # and right substring of b in xa
        # Concatenate right substring of a
        # and left substring of b in xb
        xa = a[i:j + 1]
        xb = b[i:j + 1]
 
        # Check if either of the two concatenated
        # strings is a palindrome or not
        if(xa == xa[::-1] or xb == xb[::-1]):
            return True
 
# Function to check if concatenation of splitted
# substrings of two given strings forms a palindrome
def isSplitPossible(a, b):
    if checkSplitting(a, b, len(a)) == True:
        print("Yes")
         
    elif checkSplitting(b, a, len(a)) == True:
        print("Yes")
         
    else:
        print("No")
 
 
# Given string a and b
a = "ulacfd"
b = "jizalu"
 
# Function Call
isSplitPossible(a, b)
 
 

C#




// C# program for the above approach
using System;
 
class GFG{
 
// Function to check if concatenating
// opposite subStrings after splitting
// two given Strings forms a palindrome
// or not
static bool checkSplitting(String a, String b)
{
     
    // Length of the String
    int len = a.Length;
    int i = 0, j = len - 1;
     
    // Iterate through the Strings
    while (i < len)
    {
         
        // If not a palindrome sequence
        if (a[i] != b[j])
        {
            break;
        }
        i += 1;
        j -= 1;
 
        // Concatenate left subString of a
        // and right subString of b in xa
        // Concatenate right subString of a
        // and left subString of b in xb
        String xa = a.Substring(i, j + 1 - i);
        String xb = b.Substring(i, j + 1 - i);
 
        // Check if either of the two concatenated
        // Strings is a palindrome or not
        if (xa.Equals(reverse(xa)) ||
            xb.Equals(reverse(xb)))
            return true;
    }
    return false;
}
 
// Function to check if concatenation of splitted
// subStrings of two given Strings forms a palindrome
static void isSplitPossible(String a, String b)
{
    if (checkSplitting(a, b) == true)
    {
        Console.Write("Yes");
    }
    else if (checkSplitting(b, a) == true)
    {
        Console.Write("Yes");
    }
    else
    {
        Console.Write("No");
    }
}
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);
}
   
// Driver Code
public static void Main(String[] args)
{
    String a = "ulacfd", b = "jizalu";
 
    // Function Call
    isSplitPossible(a, b);   
}
}
 
// This code is contributed by 29AjayKumar
 
 

Javascript




<script>
 
// JavaScript program for the above approach
 
// Function to check if the string is palindrome or not
 
function checkPalindrome(str) {
 
    // find the length of a string
    var len = str.length;
 
    // loop through half of the string
    for (var i = 0; i < parseInt(len / 2); i++) {
 
        // check if first and last string are same
        if (str[i] !== str[len - 1 - i]) {
            return false;
        }
    }
    return true;
}
 
// Function to check if concatenating
// opposite substrings after splitting
// two given strings forms a palindrome
// or not
function checkSplitting(a, b)
{
     
    // Length of the string
    var len = a.length;
    var i = 0, j = len - 1;
     
    // Iterate through the strings
    while (i < len)
    {
         
        // If not a palindrome sequence
        if (a[i] != b[j])
        {
            break;
        }
        i += 1;
        j -= 1;
 
        // Concatenate left substring of a
        // and right substring of b in xa
        // Concatenate right substring of a
        // and left substring of b in xb
        var xa = a.substring(i, j + 1);
        var xb = b.substring(i, j + 1);
 
        // Check if either of the two concatenated
        // strings is a palindrome or not
        if (checkPalindrome(xa)==true || checkPalindrome(xb)==true)
            return true;
    }
}
 
// Function to check if concatenation of splitted
// substrings of two given strings forms a palindrome
function isSplitPossible(a, b)
{
    if (checkSplitting(a, b) == true)
    {
       document.write( "Yes");
    }
    else if (checkSplitting(b, a) == true)
    {
        document.write("Yes");
    }
    else
    {
        document.write( "No");
    }
}
 
var a = "ulacfd", b = "jizalu";
 
    // Function Call
    isSplitPossible(a, b);
 
// This code is contributed by SoumikMondal
 
</script>
 
 
Output
Yes

Time Complexity: O(N)
Auxiliary Space: O(1)



Next Article
Count pair of strings whose concatenation of substrings form a palindrome
author
saikumarkudikala
Improve
Article Tags :
  • DSA
  • Searching
  • Strings
  • palindrome
  • partition
  • two-pointer-algorithm
Practice Tags :
  • palindrome
  • Searching
  • Strings
  • two-pointer-algorithm

Similar Reads

  • 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 "Y
    15+ min read
  • Check if given string is a substring of string formed by repeated concatenation of z to a
    Given a string str, the task is to check if string str is a substring of an infinite length string S in which lowercase alphabets are concatenated in reverse order as: S = "zyxwvutsrqponmlkjihgfedcbazyxwvutsrqponmlkjihgfedcba...." Examples: Input: str = "cbaz"Output: YES Explanation:Given string "cb
    10 min read
  • Count pair of strings whose concatenation of substrings form a palindrome
    Given an array of strings arr[], the task is to count the pair of strings whose concatenation of substrings form a palindrome.Examples: Input: arr[] = {"gfg", "gfg"} Output: 1 Explanation: One possible way of choosing s1 and s2 is s1 = "gf", s2 = "g" such that s1 + s2 i.e "gfg" is a palindrome.Input
    5 min read
  • Count of pairs of strings whose concatenation forms a palindromic string
    Given an array A[ ] consisting of N strings, the task is to count the number of pairs of possible strings that on merging forms a Palindromic String or can be rearranged to form a Palindromic String. Example : Input: N = 6, A[ ] = {aab, abcac, dffe, ed, aa, aade}Output: 6Explanation: All possible pa
    9 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
  • Find the count of palindromic sub-string of a string in its sorted form
    Given string str consisting of lowercase English alphabets, the task is to find the total number of palindromic sub-strings present in the sorted form of str. Examples: Input: str = "acbbd" Output: 6 All palindromic sub-string in it's sorted form ("abbcd") are "a", "b", "b", "bb", "c" and "d". Input
    5 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
  • Count of three non-overlapping sub-strings which on concatenation forms a palindrome
    Given a string str, the task is to count the number of ways a palindromic substring could be formed by the concatenation of three sub-strings x, y and z of the string str such that all of them are non-overlapping i.e. sub-string y occurs after substring x and sub-string z occurs after sub-string y.E
    7 min read
  • Check if it is possible to create a palindrome string from given N
    Given a number N. The task is to create an alphabetical string in lower case from that number and tell whether the string is palindrome or not. a = 0, b = 1….. and so on. For eg: If the number is 61 the substring “gb” will be printed till 7 (6+1) characters i.e. “gbgbgbg” and check if palindrome or
    7 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
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