VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-occurrences-of-anagrams/

⇱ Count Anagrams of a Pattern - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count Anagrams of a Pattern

Last Updated : 14 Mar, 2026

Given a word pattern and a string text consisting of lowercase characters, find the count of substrings in text which are anagrams of the pattern.

Examples: 

Input : text = "forxxorfxdofr", pattern = "for"
Output : 3
Explanation : Anagrams present are for, orf and ofr. Each appears in the text once and hence the count is 3.

Input : text = "aabaabaa", pattern = "aaba"
Output : 4
Explanation : Anagrams present are aaba and abaa. Each appears twice in the text and hence the count is 4.

[Naive] Substring Checking - O(n * m) time and O(1) space

Traverse the string and check every substring whose length equals the pattern. For each substring, verify whether it contains all the characters of the word.


Output
3

[Optimal] Sliding Window - O(n + m) time and O(1) space

  • Create a frequency array to track the difference between the pattern and the current window.
  • Initialize the first window by updating counts for the pattern and the first substring.
  • Slide the window one character at a time, updating counts for entering and leaving characters.
  • If all counts become zero, the current window is an anagram.

Output
3
Comment