sagelearnai

Find All Anagrams in a String

Difficulty: Medium · Pattern: Sliding Window · LeetCode #438

Return all start indices in s where a substring is an anagram of p (in increasing order). Both are lowercase letters.

Examples

text
s = "cbaebabacd", p = "abc"  →  [0, 6]
s = "abab", p = "ab"         →  [0, 1, 2]

Hints

  1. Every match has length len(p), so use a fixed-size window.
  2. Maintain 26 counts for the window and compare with p's counts.

Approach

Keep letter counts for p and for the current window of size len(p) in s. Slide the window one character at a time, incrementing the count of the entering letter and decrementing the leaving one. When the two count arrays are equal, record the window's start. Comparing 26 counts per step is O(26·n); tracking a "matches" counter makes each step O(1).

Complexity

Time: O(26·n). Space: O(1).

Python solution
def findAnagrams(s, p):
    m = len(p)
    if m > len(s):
        return []
    need, win = [0] * 26, [0] * 26
    for ch in p:
        need[ord(ch) - 97] += 1
    res = []
    for i, ch in enumerate(s):
        win[ord(ch) - 97] += 1
        if i >= m:
            win[ord(s[i - m]) - 97] -= 1
        if i >= m - 1 and win == need:
            res.append(i - m + 1)
    return res
JavaScript solution
function findAnagrams(s, p) {
  const m = p.length, res = [];
  if (m > s.length) return res;
  const need = new Array(26).fill(0), win = new Array(26).fill(0);
  for (const ch of p) need[ch.charCodeAt(0) - 97]++;
  for (let i = 0; i < s.length; i++) {
    win[s.charCodeAt(i) - 97]++;
    if (i >= m) win[s.charCodeAt(i - m) - 97]--;
    if (i >= m - 1 && win.every((v, j) => v === need[j])) res.push(i - m + 1);
  }
  return res;
}