mediumSliding WindowAmazonMicrosoft
Anagram Window Alarm
A fraud detector raises an alarm whenever any contiguous slice of an incoming message contains exactly the letters of a watch-list word.
Given lowercase strings `pattern` and `text`, return true if some substring of `text` of length `|pattern|` is an anagram of `pattern`.
Choose approach
e
0lo
i
1hi
d
2b
3a
4o
5o
6o
7Mapneed "ab"
a→1
b→1
1/5
Narrationstep 1 of 5
Need = letter counts of "ab". Initialize window = text[0..1] = "ei". match = 22/26.
Variables
lo=0
hi=1
match=22
How to think about it
- Permutation == same character multiset.
- Fixed window length == |pattern|. Slide one char at a time.
- Track one `match` scalar — count of buckets whose counts in `need` and `have` are equal.
- O(1) update on each slide: adjust 2 buckets (add + drop) and ±1 to match.
Edge cases to catch in interview
- pattern longer than text → false.
- pattern == text → true if same length AND anagram.
- Letters outside a–z would need a wider array (map).
Examples
Example 1
true{"pattern":"ab","text":"eidbaooo","values":["e","i","d","b","a","o","o","o"]}
"ba" is an anagram of "ab".
Example 2
false{"pattern":"ab","text":"eidboaoo","values":["e","i","d","b","o","a","o","o"]}
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed