Find All Anagrams

Python data engineering interview problem. Difficulty: intermediate. Pattern: Sliding Window. About 14 minutes. Part of the Pro drill bank.

Start indices of every anagram of p inside s. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.

A log search can ask for every position where a short pattern appears with its letters rearranged. Reporting all start positions is more useful than returning only the first match. Return the starting index of every substring of s that is an anagram of p, in ascending order. Each window has the same length as p and must have the same character counts. Write the function find_anagrams(s: str, p: str) -> list. For 'cbaebabacd' and 'abc', windows starting at 0 (cba) and 6 (bac) match, so the answer is [0, 6]. The starter file already has the function name and the harness print lines. Keep them, and fill only the function body.

Requirements

  • Check every contiguous window with length len(p).
  • Compare counts rather than character order.
  • Return all matching start indices in ascending order.

Constraints

  • Matching is case-sensitive and the return type is a list of integers.
  • The result has no duplicate indices, and an empty pattern has no useful non-empty window in this task.

Examples

Input: find_anagrams('cbaebabacd', 'abc') Output: [0, 6] Windows at 0 and 6 match.

Topics: lakebench, python, anagram, indices.

More Python interview questions · All interview problems · Learn data engineering

intermediate

Find All Anagrams

Interview-style drill: Start indices of every anagram of p inside s.

Implement `find_anagrams(s: str, p: str) -> list` returning start indices of anagrams of p in s, sorted ascending. Example: `"cbaebabacd", "abc"` → `[0, 6]`. Keep the harness.