Check if given string can be split into two substrings X and Y

By | September 27, 2023

Given a string str. The task is to check whether this string can be splitted into two strings X and Y such that

  • Y is a substring of X
  • X + Y = str  (Here, X+Y means X and Y are concatenated)

Examples :

Input: pleaselea
Output: Yes
str = "please" + "lea", Here "lea" is a substring of "please".

Input: woohoo
Output: Yes
str = "wooh" + "oo", Here "oo" is a substring of "wooh".

Input: split
Output: No

Approaches :

Naive approach:
Simplest approach for this problem is that

  1. Run a loop for different possibilities of string X
  2. Remaining string will be string Y
  3. Check if Y is a substring of X

Time Complexity of this approach will be O(n2 ).

Optimized approach:
Here observation is that, Y is required to be a substring of X, that means each character of Y will occur in string X in the same manner. And, Y is always a suffix of given string.

We can optimize our solution by limiting length of Y as 1. We already know that Y is a suffix and will occur in X, so last character of given string must occur in X for the given condition to be fulfilled.

Now, we will take only last character of str as string Y and check if it occurs in string X (first n-1 characters).

Below is the implementation of the above approach:

// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;

// function to check if given string 
// can be splitted in X and Y
bool splitString (string str)
{
  int n = str.length();
 
  // string Y
  char Y = str[n - 1];
  
  // find Y in remaining string
  for (int i=0; i<n-1; i++)
  {
    if (str[i] == Y)
      return true;
  }
  	
  return false;
}

// Driver Code
int main()
{
  // Given string
  string str = "pleaselea";
  	
  if (splitString(str))
    cout << "Yes" << endl;
  else
    cout << "No" << endl;

  return 0;
}

Output:

Yes

Time Complexity: O(n)
Space Complexity: O(n)

Author: Mithlesh Upadhyay

I hold an M.Tech degree in Artificial Intelligence (2023) from Delhi Technological University (DTU) and possess over 4 years of experience. I worked at GeeksforGeeks, leading teams and managing content, including GATE CS, Test Series, Placements, C, and C++. I've also contributed technical content to companies like MarsDev, Tutorialspoint, StudyTonight, TutorialCup, and Guru99. My skill set includes coding, Data Structures and Algorithms (DSA), and Object-Oriented Programming (OOPs). I'm proficient in C++, Python, JavaScript, HTML, CSS, Bootstrap, React.js, Node.js, MongoDB, Django, and Data Science.