Given strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.
s = "cbaebabacd", p = "abc"[0, 6]s
need map from p. needed = unique chars in p.have. If have[c]==need[c] → matches++have. If was matching → matches--Same as LC567 but collect all: An anagram of p must have exactly the same char frequencies in a window of size k = p.length. We check every k-length window and collect all that match.
matches counter trick: Only 2 updates per slide — add right, remove left. Each is O(1). No full array comparison. O(1) per step.
Key difference from LC567: Don't return on first match. After recording l, the window slides naturally to the next position — the loop continues until all of s is scanned.
Taking three letters at every index and sorting them repeats the same work again and again. If p is long, that becomes very slow.
Keep a fixed window, as long as p. Count the letters of p once. Each time the window slides one step, one letter comes in, and one letter goes out. Update just those two counts, and check whether the counts match.
Anagram windows are fixed windows with matching counts. Update two counts per step instead of recounting.
Run the animation above on your own input, or watch the 1:40 video explanation of Find All Anagrams in a String with a dry run and Java code.