Check if the given string is shuffled substring of another string
Last Updated :
12 Jul, 2025
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
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem