awelgorithms

Anagram window has a fixed length

Updated

An anagram of t inside s is a window whose length is m = t.length. Slide by one: add s[R], drop s[R-m]. Match when window counts equal t's counts.

What to focus on

Length never changes. This is not a covering shrink. Leftover characters sit outside [R-m+1, R], not inside a longer window.

Worked examples

hits 0 and 6

s = "cbaebabacd", t = "abc", m=3
  1. [0,2] "cba" counts match
  2. slide to [6,8] "bac" counts match

Result: L = 0 and L = 6

slide add/drop

s = "cbaebabacd", t = "abc", m=3
  1. start {c:1,b:1,a:1} match
  2. drop c add e → no
  3. … drop a add c at R=8 → {b:1,a:1,c:1} match

Result: matches at 0, 6

abca len 2

s = "abca", t = "ca", m=2
  1. "ab" no
  2. "bc" no
  3. "ca" yes

Result: L = 2

Try it

Write findAnagramWindows(s, t). s is the source string. t is the pattern. m = t.length. L is the left index of a window of length m. The window includes s[L..L+m-1]. Length stays m. Return every L whose counts match t. List L for cbaebabacd vs abc, and for abca vs ca.

s and t are nonempty. t.length ≤ s.length. At least one anagram window exists.