Count Occurrences of Anagrams Visualization & Animation

Counts all anagram occurrences of a pattern in a string using a fixed-size sliding window; O(n).

## What is it? Given a string, count the number of substrings that are anagrams of a given pattern. Two strings are anagrams if they have the same characters with the same frequencies. ## How it works **Fixed-size Sliding Window + frequency map:** - Build a frequency map for the pattern - Maintain a window of size `p.length()` over the string - As the window slides, add the incoming character and remove the outgoing character from the window map - Compare the window map with the pattern map — if equal, count it - Use a "match count" variable to avoid full map comparison each step ## When to use - Finding all anagram occurrences in a text - Problems involving permutation presence in a string ## Key Points - O(n) time — each character enters and exits the window once - O(1) space — frequency arrays of fixed size 26 - Key insight: two windows are anagrams iff their frequency arrays are identical

Category: algorithms

Difficulty: intermediate

Time Complexity: O(n)

Space Complexity: O(1)

Count Occurrences of Anagrams

intermediate

Counts all anagram occurrences of a pattern in a string using a fixed-size sliding window; O(n).

PhaseInit
Matched0/4
Count0
Pattern
a
b
c
d
b
[0]
a
[1]
c
[2]
d
[3]
g
[4]
a
[5]
b
[6]
c
[7]
d
[8]
a
[9]
Freq match
a
0/1
b
0/1
c
0/1
d
0/1
Current window
Anagram match
Evicted (slide out)
Past left pointer
Text: "bacdgabcda" Pattern: "abcd" (len=4). Count windows of size 4 that are anagrams of the pattern. Total distinct chars: 4.