# Number of sub-strings which are anagram of any sub-string of another string

Given two strings S1 and S2, the task is to count the number of sub-strings of S1 that are anagrams of any sub-string of S2.

Examples:

Input: S1 = “ABB”, S2 = “BAB”
Output: 5
There are 6 sub-strings of S1 : “A”, “B”, “B”, “AB”, “BB” and “ABB”
Out of which only “BB” is the one which is not an anagram of any sub-string of S2.

Input: S1 = “PLEASEHELPIMTRAPPED”, S2 = “INAKICKSTARTFACTORY”
Output: 9

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Naive approach: A simple approach is to check all the sub-strings of S1 against all the sub-strings of S2 whether they are anagrams or not.

Efficient approach: Take all the sub-strings of S1 one by one say temp and check whether temp is an anagram of any sub-string of S2 by calculating the frequencies of all the characters of temp and comparing it with the character frequencies of sub-strings of S2 having length = length(temp).
This can be done with a single traversal by taking the first length(temp) characters of S2 and then for every iteration, add the frequency of the next character of the string and remove the frequency of the first character of the previously chosen sub-string until the complete string is traversed.

Below is the implementation of the above approach:

 `// C++ program to find the number of sub-strings ` `// of s1 which are anagram of any sub-string of s2 ` ` `  `#include ` `using` `namespace` `std; ` ` `  `#define ALL_CHARS 256 ` ` `  `// 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 < ALL_CHARS; i++) ` `        ``if` `(arr1[i] != arr2[i]) ` `            ``return` `false``; ` ` `  `    ``return` `true``; ` `} ` ` `  `// This function search for all permutations ` `// of string pat[] in string txt[] ` `bool` `search(string pat, string txt) ` `{ ` `    ``int` `M = pat.length(); ` `    ``int` `N = txt.length(); ` ` `  `    ``int` `i; ` ` `  `    ``// countP[]: Store count of all characters ` `    ``// of pattern ` `    ``// countTW[]: Store count of current ` `    ``// window of text ` `    ``char` `countP[ALL_CHARS] = { 0 }; ` `    ``char` `countTW[ALL_CHARS] = { 0 }; ` `    ``for` `(i = 0; i < M; i++) { ` `        ``(countP[pat[i]])++; ` `        ``(countTW[txt[i]])++; ` `    ``} ` ` `  `    ``// Traverse through remaining ` `    ``// characters of pattern ` `    ``for` `(i = M; i < N; i++) { ` ` `  `        ``// Compare counts of current ` `        ``// window of text with ` `        ``// counts of pattern[] ` `        ``if` `(compare(countP, countTW)) { ` `            ``// cout<

Output:

```9
```

My Personal Notes arrow_drop_up