Check if a string can be split into two substrings such that one substring is a substring of the other

Given a string S of length N, the task is to check if a string can be split into two substrings, say A and B such that B is a substring of A. If not possible, print No. Otherwise, print Yes.

Examples :

Input: S = “abcdab”
Output: Yes
Explanation: Considering the two splits to be A=”abcd” and B=”ab”, B is a substring of A.

Input: S = “abcd”
Output: No

Naive Approach: The simplest approach to solve the problem is to split the string S at every possible index, and check if the right substring is a substring of the left substring. If any split satisfies the condition, print “Yes“. Otherwise, print “No“.
Time Complexity: O(N2)
Auxiliary Space: O(1)



Efficient Approach: To optimize the above approach, the idea is to check if the last character of the string S is present in the remaining string or not. Follow the steps below to solve the problem:

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 can be
// divided into two substrings such that
// one substring is substring of the other
void splitString(string S, int N)
{
    // Store the last character of S
    char c = S[N - 1];
  
    int f = 0;
  
    // Traverse the characters at indices [0, N-2]
    for (int i = 0; i < N - 1; i++) {
  
        // Check if the current character is
        // equal to the last character
        if (S[i] == c) {
  
            // If true, set f = 1
            f = 1;
  
            // Break out of the loop
            break;
        }
    }
  
    if (f)
        cout << "Yes";
    else
        cout << "No";
}
  
// Driver Code
int main()
{
    // Given string, S
    string S = "abcdab";
  
    // Store the size of S
    int N = S.size();
  
    // Function Call
    splitString(S, N);
  
    return 0;
}

chevron_right


Output:

Yes

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

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.