VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-a-string-contains-an-anagram-of-another-string-as-its-substring/

⇱ Check if a string contains an anagram of another string as its substring - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if a string contains an anagram of another string as its substring

Last Updated : 23 Jul, 2025

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: Yes
Explanation: String S2 contains anagram "ba" of S1 ("ba").

Input: S1 = "ab", S2 = "cbddaoo"
Output: No


 


 

Approach: Follow the steps below to solve the problem:


 

  1. Initialize two Hashmaps s1hash and s2hash, to store the frequency of alphabets of the two strings.
  2. If the length of S1 is greater than the length of S2, then print "NO".
  3. Iterate over the characters of the string S1 and update s1hash.
  4. Iterate over the characters of the string S2 using the Sliding Window technique and update the HashMap accordingly.
  5. For any substring of S2 of length equal to the length of S1, if both the Hashmaps are found to be equal, print "YES".
  6. Otherwise, print "NO".


Below is the implementation of the above approach:
 

 
 


Output: 
YES

 


 

Time Complexity: O(26 * len(S2))
Auxiliary Space: O(26)


 

Comment