Given a string S consisting of N lowercase alphabets, the task is to check if it is possible to split the string S into three non-empty substrings such that Y is the substring of the strings X and Z. If it is possible to split the string S then, print “Yes”. Otherwise, print “No”.
Input: S = “geekseekforgeeks”
The given string S = “geeksforgeeks” can be splitted as “geeks”, “eek”, and Z = “forgeeks”.
The string “eeks” is a substring of both the strings “geeks” and “forgeeks”.
Input: S = “naturalxws”
Approach: The given problem can be solved by storing the frequency of unique characters and observe the fact that if there exists any character having frequency at least 3, then the string can be split into 3 substrings satisfying the given conditions. Follow the steps below to solve the problem:
- Initialize an array, say hash, to store the frequency of characters in the string S.
- Iterate over the characters of the string and store the frequency of each character present in the string S in the array hash.
- Traverse the array hash and if the frequency of any character is greater than 2, then print “Yes” and break out of the loop.
- After completing the above steps, if there exists no such character having a frequency at least 3, then print “No”.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)