Given strings s and p, return the start indices of every substring of s that is an anagram of p, in any order.
Keep the letter counts of p minus the counts of the current window, and how many letters are still unbalanced. Sliding adds one letter on the right and removes one on the left; when nothing is unbalanced, the window is an anagram.
1function findAnagrams(s: string, p: string): number[] {2const need = new Map<string, number>();3for (const c of p) need.set(c, (need.get(c) ?? 0) + 1);4let off = need.size; const res: number[] = [];5const bump = (c: string, d: number) => {6const before = need.get(c) ?? 0, after = before + d;7need.set(c, after);8if (before === 0) off++; else if (after === 0) off--;9};10for (let r = 0; r < s.length; r++) {11bump(s[r], -1);12if (r >= p.length) bump(s[r - p.length], +1);13if (off === 0) res.push(r - p.length + 1);14}15return res;16}
Count p. 3 distinct letter(s) unbalanced.
Space: play/pause · ←/→: step