CodeArchon

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
0
lo
i
1
hi
d
2
b
3
a
4
o
5
o
6
o
7
Mapneed "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.

1def anagram_window_alarm(pattern: str, text: str) -> bool:
2 if len(pattern) > len(text):
3 return False
4 need = [0]*26
5 have = [0]*26
6 for i in range(len(pattern)):
7 need[ord(pattern[i]) - 97] += 1
8 have[ord(text[i]) - 97] += 1
9 match = sum(1 for i in range(26) if need[i] == have[i])
10 for hi in range(len(pattern), len(text)):
11 if match == 26:
12 return True
13 a = ord(text[hi]) - 97
14 have[a] += 1
15 if have[a] == need[a]:
16 match += 1
17 elif have[a] == need[a] + 1:
18 match -= 1
19 d = ord(text[hi - len(pattern)]) - 97
20 have[d] -= 1
21 if have[d] == need[d]:
22 match += 1
23 elif have[d] == need[d] - 1:
24 match -= 1
25 return match == 26
Variables
lo=0
hi=1
match=22

How to think about it

  1. Permutation == same character multiset.
  2. Fixed window length == |pattern|. Slide one char at a time.
  3. Track one `match` scalar — count of buckets whose counts in `need` and `have` are equal.
  4. 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 1true
{"pattern":"ab","text":"eidbaooo","values":["e","i","d","b","a","o","o","o"]}

"ba" is an anagram of "ab".

Example 2false
{"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