Iteration

Count Anagrams

Sliding Window

Given a string s and a shorter string t, return the total number of substrings in s\tt s that are anagrams of t\tt t.

Example:

s = "baba"t = "ab" => returns 3\notag \begin{align*} \texttt{s}&\texttt{ = "baba"}\\ \texttt{t}&\texttt{ = "ab"}\\ &\texttt{ => }\texttt{returns 3} \end{align*}

Explanation: There are 3 substrings that are anagrams of the word "ab". The first is "ba", the second is "ab", and the third is another "ba".

First Few Test Cases:

Two strings are anagrams if the count of each of their letters is the same. For example, all of these words are anagrams, because the count of each letter is the same:

To solve this problem, you can slide a window of size len(t) across the string, and compute the count of each letter in the window.

To do this efficiently, when you slide the window, you should add the 1 new letter, and remove 1 old letter, like this:

Here's how you code this up:

Time Complexity O(n)O(n). We loop over every possible window, which is O(n) iterations where n is the size of the string s. In each iteration, we check whether tCount and windowCount are the same, which takes worst-case 26 operations. This gives O(26*n) = O(n) total operations.

Space Complexity O(1)O(1). Each HashMap stores the letters a-z, which is O(26) elements. We also store the solution as an integer. This gives a total of O(26+26+1) = O(1) total space.

There's a minor optimization you can make to this code so that it takes O(n) time, instead of O(26*n) time. See below for details.

Mark as Completed:
Submits:
numberOfAnagrams
Test your code to get an output here!
numberOfAnagrams(
)
Test your code to get an output here!