Check if the given string is shuffled substring of another string
Last Updated :
17 Apr, 2023
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++
// 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;
// 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
<script>
// Javascript program to check if string
// str1 is substring of str2 or not.
// Function two check string A
// is shuffled substring of B
// or not
function isShuffledSubstring(A, B)
{
var n = A.length;
var 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 = A.split('').sort().join('');
// Traverse string B
for (var 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
var str = [];
// Copy the characters of
// string B in str till
// length n
for (var j = 0; j < n; j++)
str.push(B[i + j]);
// Sort the string str
str = str.sort()
// Return true if sorted
// string of "str" & sorted
// string of "A" are equal
if (str.join('') == A)
return true;
}
}
}
// Driver Code
// Input str1 and str2
var str1 = "geekforgeeks";
var str2 = "ekegorfkeegsgeek";
// Function return true if
// str1 is shuffled substring
// of str2
var a = isShuffledSubstring(str1, str2);
// If str1 is substring of str2
// print "YES" else print "NO"
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;
// 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<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
int 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;
}
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
<script>
// This function returns true if
// contents of arr1[] and arr2[]
// are same, otherwise false.
function compare(arr1,arr2)
{
for(let i = 0; i < 256; i++)
if (arr1[i] != arr2[i])
return false;
return true;
}
// This function search for all
// permutations of pat[] in txt[]
function search(pat,txt)
{
let M = pat.length;
let N = txt.length;
// countP[]: Store count of all
// characters of pattern
// countTW[]: Store count of
// current window of text
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)])++;
}
// Traverse through remaining
// characters of pattern
for(let 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].charCodeAt(0)])++;
// Remove the first character
// of previous window
countTW[txt[i - M].charCodeAt(0)]--;
}
// Check for the last window in text
if (compare(countP, countTW))
return true;
return false;
}
// Driver code
let txt = "BACDGABCDA";
let pat = "ABCD";
if (search(pat, txt))
document.write("Yes");
else
document.write("NO");
// This code is contributed by ab2127
</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.
Similar Reads
Check if a string is substring of another
Given two strings txt and pat, the task is to find if pat is a substring of txt. If yes, return the index of the first occurrence, else return -1.Examples : Input: txt = "geeksforgeeks", pat = "eks"Output: 2Explanation: String "eks" is present at index 2 and 9, so 2 is the smallest index.Input: txt
8 min read
Check if a string contains an anagram of another string as its substring
Given two strings S1 and S2, the task is to check if S2 contains an anagram of S1 as its substring. Examples: Input: S1 = "ab", S2 = "bbpobac"Output: YesExplanation: String S2 contains anagram "ba" of S1 ("ba"). Input: S1 = "ab", S2 = "cbddaoo"Output: No Approach: Follow the steps below to solve the
7 min read
Check if a string can be converted to another given string by removal of a substring
Given two strings S and T of length N and M respectively, the task is to check if the string S can be converted to the string T by removing at most one substring of the string S. If found to be true, then print âYESâ. Otherwise, print âNOâ. Example: Input: S = âabcdefâ, T = âabcâ Output: YES Explana
7 min read
Check if a string is a scrambled form of another string
Given two strings s1 and s2 of equal length, the task is to determine if s2 is a scrambled version of s1.A scrambled string is formed by recursively splitting the string into two non-empty substrings and rearranging them randomly (s = x + y or s = y + x) and then recursively scramble the two substri
15+ min read
Javascript Program To Check If A String Is Substring Of Another
Given two strings s1 and s2, find if s1 is a substring of s2. If yes, return the index of the first occurrence, else return -1. Examples :Â Input: s1 = "for", s2 = "geeksforgeeks" Output: 5 Explanation: String "for" is present as a substring of s2. Input: s1 = "practice", s2 = "geeksforgeeks" Output
2 min read
Check if String T can be made Substring of S by replacing given characters
Given two strings S and T and a 2D array replace[][], where replace[i] = {oldChar, newChar} represents that the character oldChar of T is replaced with newChar. The task is to find if it is possible to make string T a substring of S by replacing characters according to the replace array. Note: Each
9 min read
Queries to check if string B exists as substring in string A
Given two strings A, B and some queries consisting of an integer i, the task is to check whether the sub-string of A starting from index i and ending at index i + length(B) - 1 equals B or not. If equal then print Yes else print No. Note that i + length(B) will always be smaller than length(A). Exam
15+ min read
Check if given string is a substring of string formed by repeated concatenation of z to a
Given a string str, the task is to check if string str is a substring of an infinite length string S in which lowercase alphabets are concatenated in reverse order as: S = "zyxwvutsrqponmlkjihgfedcbazyxwvutsrqponmlkjihgfedcba...." Examples: Input: str = "cbaz"Output: YES Explanation:Given string "cb
10 min read
Find all substrings that are anagrams of another substring of the string S
Given a string S, the task is to find all the substrings in the string S which is an anagram of another different substring in the string S. The different substrings mean the substring starts at a different index. Examples: Input: S = "aba"Output: a a ab baExplanation:Following substrings are anagra
6 min read
Count of substrings of a string containing another given string as a substring | Set 2
Given two strings S and T of length N and M respectively, the task is to count the number of substrings of S that contains the string T in it as a substring. Examples: Input: S = âdabcâ, T = âabâOutput: 4Explanation:Substrings of S containing T as a substring are: S[0, 2] = âdabâS[1, 2] = âabâS[1, 3
8 min read