Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Problem: Return all start indices of anagrams of p inside s using a fixed-size window of letter counts.

Problem: Return all start indices of anagrams of p inside s using a fixed-size window of letter counts.
from collections import Counter
def anagrams(s, p):
    k, need, win, out = len(p), Counter(p), Counter(), []
    for i, c in enumerate(s):
        win[c] += 1
        if i >= k:
            win[s[i-k]] -= 1
            if win[s[i-k]] == 0: del win[s[i-k]]
        if win == need: out.append(i - k + 1)
    return out
print(anagrams("abaabaab", "aab"))
What is printed?
  1. A. [0, 1, 2, 3, 4, 5]
  2. B. [0, 3]
  3. C. [0, 2, 3, 5]
  4. D. [1, 2, 4, 5]

Correct answer: A. [0, 1, 2, 3, 4, 5]

Windows of length 3: aba, baa, aab, aba, baa, aab — every one has two a's and one b, so all six start indices 0–5 qualify. Deleting zero counts matters: Counter equality would otherwise compare a stored 0 with a missing key (Python's Counter ignores zeros in == since 3.10, but deleting is portable).

More Coding Interview Problems questions

Exams that ask this topic