# Check if the given string is shuffled substring of another string

• Difficulty Level : Medium
• Last Updated : 20 Sep, 2022

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
1. Put all the characters of str2 of length n in another string str.
2. Sort the string str and Compare str and str1.
3. If str = str1, then string str1 is a shuffled substring of string str2.
4. 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.
5. 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++

 `// C++ program to check if string``// str1 is substring of str2 or not.``#include ``using` `namespace` `std;` `// Function two check string A``// is shuffled  substring of B``// or not``bool` `isShuffledSubstring(string A, string B)``{``    ``int` `n = A.length();``    ``int` `m = B.length();` `    ``// Return false if length of``    ``// string A is greater than``    ``// length of string B``    ``if` `(n > m) {``        ``return` `false``;``    ``}``    ``else` `{` `        ``// Sort string A``        ``sort(A.begin(), A.end());` `        ``// Traverse string B``        ``for` `(``int` `i = 0; i < m; i++) {` `            ``// Return false if (i+n-1 >= m)``            ``// doesn't satisfy``            ``if` `(i + n - 1 >= m)``                ``return` `false``;` `            ``// Initialise the new string``            ``string str = ``""``;` `            ``// Copy the characters of``            ``// string B in str till``            ``// length n``            ``for` `(``int` `j = 0; j < n; j++)``                ``str.push_back(B[i + j]);` `            ``// Sort the string str``            ``sort(str.begin(), str.end());` `            ``// Return true if sorted``            ``// string of "str" & sorted``            ``// string of "A" are equal``            ``if` `(str == A)``                ``return` `true``;``        ``}``    ``}``}` `// Driver Code``int` `main()``{``    ``// Input str1 and str2``    ``string str1 = ``"geekforgeeks"``;``    ``string str2 = ``"ekegorfkeegsgeek"``;` `    ``// Function return true if``    ``// str1 is shuffled substring``    ``// of str2``    ``bool` `a = isShuffledSubstring(str1, str2);` `    ``// If str1 is substring of str2``    ``// print "YES" else print "NO"``    ``if` `(a)``        ``cout << ``"YES"``;``    ``else``        ``cout << ``"NO"``;``    ``cout << endl;``    ``return` `0;``}`

## Java

 `// Java program to check if String``// str1 is subString of str2 or not.``import` `java.util.*;` `class` `GFG``{` `// Function two check String A``// is shuffled subString of B``// or not``static` `boolean` `isShuffledSubString(String A, String B)``{``    ``int` `n = A.length();``    ``int` `m = B.length();` `    ``// Return false if length of``    ``// String A is greater than``    ``// length of String B``    ``if` `(n > m)``    ``{``        ``return` `false``;``    ``}``    ``else``    ``{` `        ``// Sort String A``        ``A = sort(A);` `        ``// Traverse String B``        ``for` `(``int` `i = ``0``; i < m; i++)``        ``{` `            ``// Return false if (i + n - 1 >= m)``            ``// doesn't satisfy``            ``if` `(i + n - ``1` `>= m)``                ``return` `false``;` `            ``// Initialise the new String``            ``String str = ``""``;` `            ``// Copy the characters of``            ``// String B in str till``            ``// length n``            ``for` `(``int` `j = ``0``; j < n; j++)``                ``str += B.charAt(i + j);` `            ``// Sort the String str``            ``str = sort(str);` `            ``// Return true if sorted``            ``// String of "str" & sorted``            ``// String of "A" are equal``            ``if` `(str.equals(A))``                ``return` `true``;``        ``}``    ``}``    ``return` `false``;``}` `// Method to sort a string alphabetically``static` `String sort(String inputString)``{``    ``// convert input string to char array``    ``char` `tempArray[] = inputString.toCharArray();``    ` `    ``// sort tempArray``    ``Arrays.sort(tempArray);``    ` `    ``// return new sorted string``    ``return` `String.valueOf(tempArray);``}` `// Driver Code``public` `static` `void` `main(String[] args)``{``    ``// Input str1 and str2``    ``String str1 = ``"geekforgeeks"``;``    ``String str2 = ``"ekegorfkeegsgeek"``;` `    ``// Function return true if``    ``// str1 is shuffled subString``    ``// of str2``    ``boolean` `a = isShuffledSubString(str1, str2);` `    ``// If str1 is subString of str2``    ``// print "YES" else print "NO"``    ``if` `(a)``        ``System.out.print(``"YES"``);``    ``else``        ``System.out.print(``"NO"``);``    ``System.out.println();``}``}` `// This code is contributed by PrinciRaj1992`

## Python3

 `# Python3 program to check if string``# str1 is subof str2 or not.` `# Function two check A``# is shuffled subof B``# or not``def` `isShuffledSubstring(A, B):``    ``n ``=` `len``(A)``    ``m ``=` `len``(B)` `    ``# Return false if length of``    ``# A is greater than``    ``# length of B``    ``if` `(n > m):``        ``return` `False``    ``else``:` `        ``# Sort A``        ``A ``=` `sorted``(A)` `        ``# Traverse B``        ``for` `i ``in` `range``(m):` `            ``# Return false if (i+n-1 >= m)``            ``# doesn't satisfy``            ``if` `(i ``+` `n ``-` `1` `>``=` `m):``                ``return` `False` `            ``# Initialise the new string``            ``Str` `=` `""` `            ``# Copy the characters of``            ``# B in str till``            ``# length n``            ``for` `j ``in` `range``(n):``                ``Str` `+``=` `(B[i ``+` `j])` `            ``# Sort the str``            ``Str` `=` `sorted``(``Str``)` `            ``# Return true if sorted``            ``# of "str" & sorted``            ``# of "A" are equal``            ``if` `(``Str` `=``=` `A):``                ``return` `True` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ` `    ``# Input str1 and str2``    ``Str1 ``=` `"geekforgeeks"``    ``Str2 ``=` `"ekegorfkeegsgeek"` `    ``# Function return true if``    ``# str1 is shuffled substring``    ``# of str2``    ``a ``=` `isShuffledSubstring(Str1, Str2)` `    ``# If str1 is subof str2``    ``# print "YES" else print "NO"``    ``if` `(a):``        ``print``(``"YES"``)``    ``else``:``        ``print``(``"NO"``)` `# This code is contributed by mohit kumar 29`

## C#

 `// C# program to check if String``// str1 is subString of str2 or not.``using` `System;` `public` `class` `GFG``{`` ` `// Function two check String A``// is shuffled subString of B``// or not``static` `bool` `isShuffledSubString(String A, String B)``{``    ``int` `n = A.Length;``    ``int` `m = B.Length;`` ` `    ``// Return false if length of``    ``// String A is greater than``    ``// length of String B``    ``if` `(n > m)``    ``{``        ``return` `false``;``    ``}``    ``else``    ``{`` ` `        ``// Sort String A``        ``A = sort(A);`` ` `        ``// Traverse String B``        ``for` `(``int` `i = 0; i < m; i++)``        ``{`` ` `            ``// Return false if (i + n - 1 >= m)``            ``// doesn't satisfy``            ``if` `(i + n - 1 >= m)``                ``return` `false``;`` ` `            ``// Initialise the new String``            ``String str = ``""``;`` ` `            ``// Copy the characters of``            ``// String B in str till``            ``// length n``            ``for` `(``int` `j = 0; j < n; j++)``                ``str += B[i + j];`` ` `            ``// Sort the String str``            ``str = sort(str);`` ` `            ``// Return true if sorted``            ``// String of "str" & sorted``            ``// String of "A" are equal``            ``if` `(str.Equals(A))``                ``return` `true``;``        ``}``    ``}``    ``return` `false``;``}`` ` `// Method to sort a string alphabetically``static` `String sort(String inputString)``{``    ``// convert input string to char array``    ``char` `[]tempArray = inputString.ToCharArray();``     ` `    ``// sort tempArray``    ``Array.Sort(tempArray);``     ` `    ``// return new sorted string``    ``return` `String.Join(``""``,tempArray);``}`` ` `// Driver Code``public` `static` `void` `Main(String[] args)``{``    ``// Input str1 and str2``    ``String str1 = ``"geekforgeeks"``;``    ``String str2 = ``"ekegorfkeegsgeek"``;`` ` `    ``// Function return true if``    ``// str1 is shuffled subString``    ``// of str2``    ``bool` `a = isShuffledSubString(str1, str2);`` ` `    ``// If str1 is subString of str2``    ``// print "YES" else print "NO"``    ``if` `(a)``        ``Console.Write(``"YES"``);``    ``else``        ``Console.Write(``"NO"``);``    ``Console.WriteLine();``}``}` `// This code is contributed by PrinciRaj1992`

## Javascript

 ``

Output:

`YES`

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``#include``#define MAX 256``using` `namespace` `std;` `// This function returns true if contents of arr1[] and arr2[]``// are same, otherwise false.``bool` `compare(``int` `arr1[], ``int` `arr2[])``{``    ``for` `(``int` `i=0; i

## Java

 `import` `java.util.*;` `class` `GFG{` `// This function returns true if``// contents of arr1[] and arr2[]``// are same, otherwise false.``static` `boolean` `compare(``int` `[]arr1, ``int` `[]arr2)``{``    ``for``(``int` `i = ``0``; i < ``256``; i++)``        ``if` `(arr1[i] != arr2[i])``            ``return` `false``;``            ` `    ``return` `true``;``}` `// This function search for all``// permutations of pat[] in txt[]``static` `boolean` `search(String pat, String txt)``{``    ``int` `M = pat.length();``    ``int` `N = txt.length();``    ` `    ``// countP[]: Store count of all``    ``// characters of pattern``    ``// countTW[]: Store count of``    ``// current window of text``    ``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)])++;``    ``}` `    ``// Traverse through remaining``    ``// characters of pattern``    ``for``(``int` `i = M; i < N; i++)``    ``{``        ` `        ``// Compare counts of current``        ``// window of text with``        ``// counts of pattern[]``        ``if` `(compare(countP, countTW))``            ``return` `true``;` `        ``// Add current character to``        ``// current window``        ``(countTW[txt.charAt(i)])++;` `        ``// Remove the first character``        ``// of previous window``        ``countTW[txt.charAt(i - M)]--;``    ``}` `    ``// Check for the last window in text``    ``if` `(compare(countP, countTW))``        ``return` `true``;``        ``return` `false``;``}` `// Driver code``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"``);``}``}` `// This code is contributed by Stream_Cipher`

## Python3

 `MAX` `=` `256` `# This function returns true if contents``# of arr1[] and arr2[] are same,``# otherwise false.``def` `compare(arr1, arr2):``    ` `    ``global` `MAX` `    ``for` `i ``in` `range``(``MAX``):``        ``if` `(arr1[i] !``=` `arr2[i]):``            ``return` `False``            ` `    ``return` `True` `# This function search for all permutations``# of pat[] in txt[]``def` `search(pat, txt):``    ` `    ``M ``=` `len``(pat)``    ``N ``=` `len``(txt)` `    ``# countP[]: Store count of all characters``    ``#           of pattern``    ``# countTW[]: Store count of current window``    ``#            of text``    ``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` `    ``# Traverse through remaining``    ``# characters of pattern``    ``for` `i ``in` `range``(M, N):``        ` `        ``# Compare counts of current window``        ``# of text with counts of pattern[]``        ``if` `(compare(countP, countTW)):``            ``return` `True``            ` `        ``# Add current character``        ``# to current window``        ``countTW[``ord``(txt[i])] ``+``=` `1` `        ``# Remove the first character``        ``# of previous window``        ``countTW[``ord``(txt[i ``-` `M])] ``-``=` `1` `    ``# Check for the last window in text``    ``if``(compare(countP, countTW)):``        ``return` `True``        ``return` `False` `# Driver code``txt ``=` `"BACDGABCDA"``pat ``=` `"ABCD"` `if` `(search(pat, txt)):``    ``print``(``"Yes"``)``else``:``    ``print``(``"No"``)` `# This code is contributed by avanitrachhadiya2155`

## C#

 `using` `System.Collections.Generic;``using` `System;` `class` `GFG{` `// This function returns true if``// contents of arr1[] and arr2[]``// are same, otherwise false.``static` `bool` `compare(``int` `[]arr1, ``int` `[]arr2)``{``    ``for``(``int` `i = 0; i < 256; i++)``        ``if` `(arr1[i] != arr2[i])``            ``return` `false``;``            ` `    ``return` `true``;``}` `// This function search for all``// permutations of pat[] in txt[]``static` `bool` `search(String pat, String txt)``{``    ``int` `M = pat.Length;``    ``int` `N = txt.Length;` `    ``// countP[]: Store count of all``    ``// characters of pattern``    ``// countTW[]: Store count of``    ``// current window of text``    ``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]])++;``    ``}` `    ``// Traverse through remaining``    ``// characters of pattern``    ``for``(``int` `i = M; i < N; i++)``    ``{``        ` `        ``// Compare counts of current``        ``// window of text with``        ``// counts of pattern[]``        ``if` `(compare(countP, countTW))``            ``return` `true``;` `        ``// Add current character to``        ``// current window``        ``(countTW[txt[i]])++;` `        ``// Remove the first character``        ``// of previous window``        ``countTW[txt[i - M]]--;``    ``}` `    ``// Check for the last window in text``    ``if` `(compare(countP, countTW))``        ``return` `true``;``        ``return` `false``;``}` `// Driver code``public` `static` `void` `Main()``{``    ``string` `txt = ``"BACDGABCDA"``;``    ``string` `pat = ``"ABCD"``;``    ` `    ``if` `(search(pat, txt))``        ``Console.WriteLine(``"Yes"``);``    ``else``        ``Console.WriteLine(``"NO"``);``}``}` `// This code is contributed by Stream_Cipher`

## Javascript

 ``

Output:

`Yes`

My Personal Notes arrow_drop_up