Check if the given string is shuffled substring of another string

Given strings str1 and str2. The task is to find that if str1 is substring in shuffled form of str2 or not. Print “YES” if str1 is 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 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 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:

CPP

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to check if string
// str1 is substring of str2 or not.
#include <bits/stdc++.h>
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;
  
            // Intialise 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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
  
            // Intialise 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 

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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
  
            # Intialise 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
   
            // Intialise 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

chevron_right


Output:

YES
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 256 possible characters in ASCII. The idea is to use two count arrays:

1) The first count array store frequencies of characters in pattern.
2) The second count array stores frequencies of characters in current window of text.

The important thing to note is, time complexity to compare two count arrays is O(1) as the number of elements in them are fixed (independent of pattern and text sizes). 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 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 first character in previous window in countWT[]

3) The last window is not checked by above loop, so explicitly check it.

Following is the implementation of above algorithm.

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<iostream> 
#include<cstring> 
#define MAX 256 
using namespace std; 
  
// This function returns true if contents of arr1[] and arr2[] 
// are same, otherwise false. 
bool compare(char arr1[], char arr2[]) 
    for (int i=0; i<MAX; i++) 
        if (arr1[i] != arr2[i]) 
            return false
    return true
  
// This function search for all permutations of pat[] in txt[] 
bool search(char *pat, char *txt) 
    int M = strlen(pat), N = strlen(txt); 
  
    // countP[]: Store count of all characters of pattern 
    // countTW[]: Store count of current window of text 
    char countP[MAX] = {0}, countTW[MAX] = {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 program to test above function */
int main() 
    char txt[] = "BACDGABCDA"
    char pat[] = "ABCD"
    if (search(pat, txt))
       cout << "Yes";
    else
       cout << "No"
    return 0; 

chevron_right


Output:

Yes



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.