Check if a string can be split into 3 substrings such that one of them is a substring of the other two
Last Updated :
03 May, 2021
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”.
Examples:
Input: S = “geekseekforgeeks”
Output: Yes
Explanation:
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”
Output: No
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:
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
string freqCheck(string S, int N)
{
int hash[26] = { 0 };
for ( int i = 0; i < N; i++) {
hash[S[i] - 'a' ]++;
}
for ( int i = 0; i < 26; i++) {
if (hash[i] > 2) {
return "Yes" ;
}
}
return "No" ;
}
int main()
{
string S = "geekseekforgeeks" ;
int N = S.length();
cout << freqCheck(S, N);
return 0;
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG{
static String freqCheck(String S, int N)
{
int hash[] = new int [ 26 ];
for ( int i = 0 ; i < N; i++)
{
hash[S.charAt(i) - 'a' ]++;
}
for ( int i = 0 ; i < 26 ; i++)
{
if (hash[i] > 2 )
{
return "Yes" ;
}
}
return "No" ;
}
public static void main(String[] args)
{
String S = "geekseekforgeeks" ;
int N = S.length();
System.out.println(freqCheck(S, N));
}
}
|
Python3
def freqCheck(S, N):
hash = [ 0 ] * 26
for i in range (N):
hash [ ord (S[i]) - ord ( 'a' )] + = 1
for i in range ( 26 ):
if ( hash [i] > 2 ):
return "Yes"
return "No"
if __name__ = = "__main__" :
S = "geekseekforgeeks"
N = len (S)
print (freqCheck(S, N))
|
C#
using System;
class GFG{
static string freqCheck( string S, int N)
{
int [] hash = new int [26];
for ( int i = 0; i < N; i++)
{
hash[S[i] - 'a' ]++;
}
for ( int i = 0; i < 26; i++)
{
if (hash[i] > 2)
{
return "Yes" ;
}
}
return "No" ;
}
static public void Main()
{
string S = "geekseekforgeeks" ;
int N = S.Length;
Console.WriteLine(freqCheck(S, N));
}
}
|
Javascript
<script>
function freqCheck(S, N){
let hash = new Array(26).fill(0)
for (let i = 0; i < N; i++){
hash[S.charCodeAt(i) - 'a' .charCodeAt(0)] += 1
}
for (let i = 0; i < 26; i++){
if (hash[i] > 2){
return "Yes"
}
}
return "No"
}
let S = "geekseekforgeeks"
let N = S.length
document.write(freqCheck(S, N))
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...