Check if the given string is shuffled substring of another string
Given strings str1 and str2. The task is to find if str1 is a substring in the shuffled form of str2 or not. Print “YES” if str1 is a substring in shuffled form of str2 else print “NO”.
Example
Input: str1 = “onetwofour”, str2 = “hellofourtwooneworld”
Output: YES
Explanation: str1 is substring in shuffled form of str2 as
str2 = “hello” + “fourtwoone” + “world”
str2 = “hello” + str1 + “world”, where str1 = “fourtwoone” (shuffled form)
Hence, str1 is a substring of str2 in shuffled form.
Input: str1 = “roseyellow”, str2 = “yellow”
Output: NO
Explanation: As the length of str1 is greater than str2. Hence, str1 is not a substring of str2.
Approach:
Let n = length of str1, m = length of str2.
- If n > m, then string str1 can never be the substring of str2.
- Else sort the string str1.
- Traverse string str2
- Put all the characters of str2 of length n in another string str.
- Sort the string str and Compare str and str1.
- If str = str1, then string str1 is a shuffled substring of string str2.
- else repeat the above process till ith index of str2 such that (i +n – 1 > m)(as after this index the length of remaining string str2 will be less than str1.
- If str is not equals to str1 in above steps, then string str1 can never be substring of str2.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isShuffledSubstring(string A, string B)
{
int n = A.length();
int m = B.length();
if (n > m) {
return false ;
}
else {
sort(A.begin(), A.end());
for ( int i = 0; i < m; i++) {
if (i + n - 1 >= m)
return false ;
string str = "" ;
for ( int j = 0; j < n; j++)
str.push_back(B[i + j]);
sort(str.begin(), str.end());
if (str == A)
return true ;
}
}
}
int main()
{
string str1 = "geekforgeeks" ;
string str2 = "ekegorfkeegsgeek" ;
bool a = isShuffledSubstring(str1, str2);
if (a)
cout << "YES" ;
else
cout << "NO" ;
cout << endl;
return 0;
}
|
Java
import java.util.*;
class GFG
{
static boolean isShuffledSubString(String A, String B)
{
int n = A.length();
int m = B.length();
if (n > m)
{
return false ;
}
else
{
A = sort(A);
for ( int i = 0 ; i < m; i++)
{
if (i + n - 1 >= m)
return false ;
String str = "" ;
for ( int j = 0 ; j < n; j++)
str += B.charAt(i + j);
str = sort(str);
if (str.equals(A))
return true ;
}
}
return false ;
}
static String sort(String inputString)
{
char tempArray[] = inputString.toCharArray();
Arrays.sort(tempArray);
return String.valueOf(tempArray);
}
public static void main(String[] args)
{
String str1 = "geekforgeeks" ;
String str2 = "ekegorfkeegsgeek" ;
boolean a = isShuffledSubString(str1, str2);
if (a)
System.out.print( "YES" );
else
System.out.print( "NO" );
System.out.println();
}
}
|
Python3
def isShuffledSubstring(A, B):
n = len (A)
m = len (B)
if (n > m):
return False
else :
A = sorted (A)
for i in range (m):
if (i + n - 1 > = m):
return False
Str = ""
for j in range (n):
Str + = (B[i + j])
Str = sorted ( Str )
if ( Str = = A):
return True
if __name__ = = '__main__' :
Str1 = "geekforgeeks"
Str2 = "ekegorfkeegsgeek"
a = isShuffledSubstring(Str1, Str2)
if (a):
print ( "YES" )
else :
print ( "NO" )
|
C#
using System;
public class GFG
{
static bool isShuffledSubString(String A, String B)
{
int n = A.Length;
int m = B.Length;
if (n > m)
{
return false ;
}
else
{
A = sort(A);
for ( int i = 0; i < m; i++)
{
if (i + n - 1 >= m)
return false ;
String str = "" ;
for ( int j = 0; j < n; j++)
str += B[i + j];
str = sort(str);
if (str.Equals(A))
return true ;
}
}
return false ;
}
static String sort(String inputString)
{
char []tempArray = inputString.ToCharArray();
Array.Sort(tempArray);
return String.Join( "" ,tempArray);
}
public static void Main(String[] args)
{
String str1 = "geekforgeeks" ;
String str2 = "ekegorfkeegsgeek" ;
bool a = isShuffledSubString(str1, str2);
if (a)
Console.Write( "YES" );
else
Console.Write( "NO" );
Console.WriteLine();
}
}
|
Javascript
<script>
function isShuffledSubstring(A, B)
{
var n = A.length;
var m = B.length;
if (n > m) {
return false ;
}
else {
A = A.split( '' ).sort().join( '' );
for ( var i = 0; i < m; i++) {
if (i + n - 1 >= m)
return false ;
var str = [];
for ( var j = 0; j < n; j++)
str.push(B[i + j]);
str = str.sort()
if (str.join('') == A)
return true ;
}
}
}
var str1 = "geekforgeeks" ;
var str2 = "ekegorfkeegsgeek" ;
var a = isShuffledSubstring(str1, str2);
if (a)
document.write( "YES" );
else
document.write( "NO" );
document.write( "<br>" );
</script>
|
Time Complexity: O(m*n*log(n)), where n = length of string str1 and m = length of string str2
Auxiliary Space: O(n)
Efficient Solution: This problem is a simpler version of Anagram Search. It can be solved in linear time using character frequency counting.
We can achieve O(n) time complexity under the assumption that alphabet size is fixed which is typically true as we have maximum of 256 possible characters in ASCII. The idea is to use two count arrays:
1) The first count array stores frequencies of characters in a pattern.
2) The second count array stores frequencies of characters in the current window of text.
The important thing to note is, time complexity to compare two counted arrays is O(1) as the number of elements in them is fixed (independent of pattern and text sizes). The following are steps of this algorithm.
1) Store counts of frequencies of pattern in first count array countP[]. Also, store counts of frequencies of characters in the first window of text in array countTW[].
2) Now run a loop from i = M to N-1. Do following in loop.
…..a) If the two count arrays are identical, we found an occurrence.
…..b) Increment count of current character of text in countTW[]
…..c) Decrement count of the first character in the previous window in countWT[]
3) The last window is not checked by the above loop, so explicitly check it.
The following is the implementation of the above algorithm.
C++
#include<iostream>
#include<cstring>
#define MAX 256
using namespace std;
bool compare( int arr1[], int arr2[])
{
for ( int i=0; i<MAX; i++)
if (arr1[i] != arr2[i])
return false ;
return true ;
}
bool search( char *pat, char *txt)
{
int M = strlen (pat), N = strlen (txt);
int countP[MAX] = {0}, countTW[MAX] = {0};
for ( int i = 0; i < M; i++)
{
countP[pat[i]]++;
countTW[txt[i]]++;
}
for ( int i = M; i < N; i++)
{
if (compare(countP, countTW))
return true ;
(countTW[txt[i]])++;
countTW[txt[i-M]]--;
}
if (compare(countP, countTW))
return true ;
return false ;
}
int main()
{
char txt[] = "BACDGABCDA" ;
char pat[] = "ABCD" ;
if (search(pat, txt))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.util.*;
class GFG{
static boolean compare( int []arr1, int []arr2)
{
for ( int i = 0 ; i < 256 ; i++)
if (arr1[i] != arr2[i])
return false ;
return true ;
}
static boolean search(String pat, String txt)
{
int M = pat.length();
int N = txt.length();
int []countP = new int [ 256 ];
int []countTW = new int [ 256 ];
for ( int i = 0 ; i < 256 ; i++)
{
countP[i] = 0 ;
countTW[i] = 0 ;
}
for ( int i = 0 ; i < M; i++)
{
(countP[pat.charAt(i)])++;
(countTW[txt.charAt(i)])++;
}
for ( int i = M; i < N; i++)
{
if (compare(countP, countTW))
return true ;
(countTW[txt.charAt(i)])++;
countTW[txt.charAt(i - M)]--;
}
if (compare(countP, countTW))
return true ;
return false ;
}
public static void main(String[] args)
{
String txt = "BACDGABCDA" ;
String pat = "ABCD" ;
if (search(pat, txt))
System.out.println( "Yes" );
else
System.out.println( "NO" );
}
}
|
Python3
MAX = 256
def compare(arr1, arr2):
global MAX
for i in range ( MAX ):
if (arr1[i] ! = arr2[i]):
return False
return True
def search(pat, txt):
M = len (pat)
N = len (txt)
countP = [ 0 for i in range ( MAX )]
countTW = [ 0 for i in range ( MAX )]
for i in range (M):
countP[ ord (pat[i])] + = 1
countTW[ ord (txt[i])] + = 1
for i in range (M, N):
if (compare(countP, countTW)):
return True
countTW[ ord (txt[i])] + = 1
countTW[ ord (txt[i - M])] - = 1
if (compare(countP, countTW)):
return True
return False
txt = "BACDGABCDA"
pat = "ABCD"
if (search(pat, txt)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System.Collections.Generic;
using System;
class GFG{
static bool compare( int []arr1, int []arr2)
{
for ( int i = 0; i < 256; i++)
if (arr1[i] != arr2[i])
return false ;
return true ;
}
static bool search(String pat, String txt)
{
int M = pat.Length;
int N = txt.Length;
int []countP = new int [256];
int []countTW = new int [256];
for ( int i = 0; i < 256; i++)
{
countP[i] = 0;
countTW[i] = 0;
}
for ( int i = 0; i < M; i++)
{
(countP[pat[i]])++;
(countTW[txt[i]])++;
}
for ( int i = M; i < N; i++)
{
if (compare(countP, countTW))
return true ;
(countTW[txt[i]])++;
countTW[txt[i - M]]--;
}
if (compare(countP, countTW))
return true ;
return false ;
}
public static void Main()
{
string txt = "BACDGABCDA" ;
string pat = "ABCD" ;
if (search(pat, txt))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "NO" );
}
}
|
Javascript
<script>
function compare(arr1,arr2)
{
for (let i = 0; i < 256; i++)
if (arr1[i] != arr2[i])
return false ;
return true ;
}
function search(pat,txt)
{
let M = pat.length;
let N = txt.length;
let countP = new Array(256);
let countTW = new Array(256);
for (let i = 0; i < 256; i++)
{
countP[i] = 0;
countTW[i] = 0;
}
for (let i = 0; i < 256; i++)
{
countP[i] = 0;
countTW[i] = 0;
}
for (let i = 0; i < M; i++)
{
(countP[pat[i].charCodeAt(0)])++;
(countTW[txt[i].charCodeAt(0)])++;
}
for (let i = M; i < N; i++)
{
if (compare(countP, countTW))
return true ;
(countTW[txt[i].charCodeAt(0)])++;
countTW[txt[i - M].charCodeAt(0)]--;
}
if (compare(countP, countTW))
return true ;
return false ;
}
let txt = "BACDGABCDA" ;
let pat = "ABCD" ;
if (search(pat, txt))
document.write( "Yes" );
else
document.write( "NO" );
</script>
|
Time Complexity: O(M + (N-M)*256) where M is size of input string pat and N is size of input string txt. This is because one for loop runs from 0 to M and contributes O(M) time. Also, another for loop runs from M to N in which compare function is executed which runs in O(256) time which consequently results in O((N-m)*256) time complexity. So overall time complexity becomes O(M + (N-M)*256).
Space Complexity: O(256) as countP and countTW arrays of size MAX i.e, 256 has been created.
Last Updated :
17 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...