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

03 Jun, 2021
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 problem:
 
Initialize two Hashmaps s1hash and s2hash, to store the frequency of alphabets of the two strings.If the length of S1 is greater than the length of S2, then print “NO”.Iterate over the characters of the string S1 and update s1hash.Iterate over the characters of the string S2 using the Sliding Window technique and update the HashMap accordingly.For any substring of S2 of length equal to the length of S1, if both the Hashmaps are found to be equal, print “YES”.Otherwise, print “NO”.
Initialize two Hashmaps s1hash and s2hash, to store the frequency of alphabets of the two strings.
If the length of S1 is greater than the length of S2, then print “NO”.
Iterate over the characters of the string S1 and update s1hash.
Iterate over the characters of the string S2 using the Sliding Window technique and update the HashMap accordingly.
For any substring of S2 of length equal to the length of S1, if both the Hashmaps are found to be equal, print “YES”.
Otherwise, print “NO”.
Below is the implementation of the above approach: 
C++
Java
Python3
C#
Javascript
// C++ Program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to check if string s2// contains anagram of the string// s1 as its substringbool checkAnagram(string s1, string s2){    // Stores frequencies of    // characters in substrings of s2    vector<int> s2hash(26, 0);     // Stores frequencies of    // characters in s1    vector<int> s1hash(26, 0);    int s1len = s1.size();    int s2len = s2.size();     // If length of s2 exceeds length of s1    if (s1len > s2len)        return false;     int left = 0, right = 0;     // Store frequencies of characters in first    // substring of length s1len in string s2    while (right < s1len) {         s1hash[s1[right] - 'a'] += 1;        s2hash[s2[right] - 'a'] += 1;        right++;    }     right -= 1;     // Perform Sliding Window technique    while (right < s2len) {         // If hashmaps are found to be        // identical for any substring        if (s1hash == s2hash)            return true;         right++;         if (right != s2len)            s2hash[s2[right] - 'a'] += 1;         s2hash[s2[left] - 'a'] -= 1;        left++;    }    return false;} // Driver Codeint main(){    string s1 = "ab";    string s2 = "bbpobac";     if (checkAnagram(s1, s2))        cout << "YES\n";    else        cout << "No\n";     return 0;}
// Java program for the above approachimport java.io.*;import java.util.*;class GFG{   // Function to check if string s2  // contains anagram of the string  // s1 as its substring  public static boolean checkAnagram(String s1, String s2)  {     // Stores frequencies of    // characters in substrings of s2    int s2hash[] = new int[26];     // Stores frequencies of    // characters in s1    int s1hash[] = new int[26];    int s1len = s1.length();    int s2len = s2.length();     // If length of s2 exceeds length of s1    if (s1len > s2len)      return false;    int left = 0, right = 0;     // Store frequencies of characters in first    // substring of length s1len in string s2    while (right < s1len)    {      s1hash[s1.charAt(right) - 'a'] += 1;      s2hash[s2.charAt(right) - 'a'] += 1;      right++;    }     right -= 1;     // Perform Sliding Window technique    while (right < s2len) {       // If hashmaps are found to be      // identical for any substring      if (Arrays.equals(s1hash, s2hash))        return true;       right++;       if (right != s2len)        s2hash[s2.charAt(right) - 'a'] += 1;       s2hash[s2.charAt(left) - 'a'] -= 1;      left++;    }    return false;  }   // Driver Code  public static void main(String[] args)  {     String s1 = "ab";    String s2 = "bbpobac";     if (checkAnagram(s1, s2))      System.out.println("YES");    else      System.out.println("No");  }} // This code is contributed by kingash.
# Python 3 Program to implement# the above approach # Function to check if string s2# contains anagram of the string# s1 as its substringdef checkAnagram(s1, s2):    # Stores frequencies of    # characters in substrings of s2    s2hash = [0 for i in range(26)]     # Stores frequencies of    # characters in s1    s1hash = [0 for i in range(26)]    s1len = len(s1)    s2len = len(s2)     # If length of s2 exceeds length of s1    if (s1len > s2len):        return False     left = 0    right = 0     # Store frequencies of characters in first    # substring of length s1len in string s2    while (right < s1len):        s1hash[ord(s1[right]) - 97] += 1        s2hash[ord(s2[right]) - 97] += 1        right += 1     right -= 1     # Perform Sliding Window technique    while (right < s2len):        # If hashmaps are found to be        # identical for any substring        if (s1hash == s2hash):            return True        right += 1         if (right != s2len):            s2hash[ord(s2[right]) - 97] += 1         s2hash[ord(s2[left]) - 97] -= 1        left += 1     return False # Driver Codeif __name__ == '__main__':    s1 = "ab"    s2 = "bbpobac"     if (checkAnagram(s1, s2)):        print("YES")    else:        print("No")                 # This code is contributed by ipg2016107
// C# Program to implement// the above approachusing System;using System.Collections.Generic;class GFG{    // Function to check if string s2// contains anagram of the string// s1 as its substringstatic bool checkAnagram(string s1, string s2){    // Stores frequencies of    // characters in substrings of s2    List<int> s2hash = new List<int>();    for(int i=0;i<26;i++)        s2hash.Add(0);     // Stores frequencies of    // characters in s1    List<int> s1hash = new List<int>();    for(int i=0;i<26;i++)        s1hash.Add(0);    int s1len = s1.Length;    int s2len = s2.Length;     // If length of s2 exceeds length of s1    if (s1len > s2len)        return false;     int left = 0, right = 0;     // Store frequencies of characters in first    // substring of length s1len in string s2    while (right < s1len) {         s1hash[s1[right] - 'a'] += 1;        s2hash[s2[right] - 'a'] += 1;        right++;    }     right -= 1;     // Perform Sliding Window technique    while (right < s2len) {         // If hashmaps are found to be        // identical for any substring        if (s1hash == s2hash)            return true;         right++;         if(right != s2len)            s2hash[s2[right] - 'a'] += 1;         s2hash[s2[left] - 'a'] -= 1;        left++;    }    return false;} // Driver Codepublic static void Main(){    string s1 = "ab";    string s2 = "bbpobac";     if (checkAnagram(s1, s2)==true)        Console.WriteLine("NO");    else        Console.WriteLine("YES");}} // This code is contributed by bgangawar59.
<script> // Javascript Program to implement// the above approach // Function to check if string s2// contains anagram of the string// s1 as its substringfunction checkAnagram(s1, s2){    // Stores frequencies of    // characters in substrings of s2    var s2hash = Array(26).fill(0);     // Stores frequencies of    // characters in s1    var s1hash = Array(26).fill(0);    var s1len = s1.length;    var s2len = s2.length;     // If length of s2 exceeds length of s1    if (s1len > s2len)        return false;     var left = 0, right = 0;     // Store frequencies of characters in first    // substring of length s1len in string s2    while (right < s1len) {         s1hash[s1[right].charCodeAt(0) - 'a'.charCodeAt(0)] += 1;        s2hash[s2[right].charCodeAt(0) - 'a'.charCodeAt(0)] += 1;        right++;    }     right -= 1;     // Perform Sliding Window technique    while (right < s2len) {         var ans = true;         // If hashmaps are found to be        // identical for any substring        for(var i =0; i<26; i++)        {            if(s1hash[i]!=s2hash[i])            {                ans = false;            }        }         if(ans)            return true;         right++;         if (right != s2len)            s2hash[s2[right].charCodeAt(0) - 'a'.charCodeAt(0)] += 1;         s2hash[s2[left].charCodeAt(0) - 'a'.charCodeAt(0)] -= 1;        left++;    }    return false;} // Driver Codevar s1 = "ab";var s2 = "bbpobac";if (checkAnagram(s1, s2))    document.write( "YES");else    document.write( "No"); // This code is contributed by importantly.</script>
  
YES
 
 
Time Complexity: O(26 * len(S2))Auxiliary Space: O(26)
 
ipg2016107
bgangwar59
Kingash
importantly
anagram
frequency-counting
sliding-window
substring
Technical Scripter 2020
Hash
Searching
Strings
Technical Scripter
sliding-window
Searching
Hash
Strings
anagram
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Quadratic Probing in Hashing
Rearrange an array such that arr[i] = i
Hashing in Java
Practice Problems on Hashing
Hash Functions and list/types of Hash functions
Binary Search
Linear Search
Maximum and minimum of an array using minimum number of comparisons
Find the Missing Number
K'th Smallest/Largest Element in Unsorted Array | Set 1