Data Structures & AlgorithmsModerateProduct Company SDE · sliding window OA

Problem: Count the start indices i where a permutation of 'abc' begins in s = 'cbaebabacd' (the anagram-window problem). Run the code.

Problem: Count the start indices i where a permutation of 'abc' begins in s = 'cbaebabacd' (the anagram-window problem). Run the code.
from collections import Counter
s, p = 'cbaebabacd', 'abc'
need = Counter(p)
print(sum(1 for i in range(len(s) - len(p) + 1) if Counter(s[i:i + len(p)]) == need))
What is printed?
  1. A. 1
  2. B. 3
  3. C. 2
  4. D. 4

Correct answer: C. 2

The windows 'cba' at index 0 and 'bac' at index 6 are anagrams of 'abc'. Checking only the first window gives the trap 1.

More Coding Interview Problems questions

Exams that ask this topic