← All Exercises
Find All Anagrams in a String
intermediatepython
Background
Anagram windows appear in plagiarism detection, log signature matching, and DNA motif discovery.
Problem
Given a string s and a pattern p, return every start index where a contiguous substring of s is an anagram of p.
Input
A text string s and a pattern string p, each up to 100000 lowercase letters.
Output
An ascending list of zero-based start indices, empty when no anagram occurs.
Sample tests
Sample 1
Input: s = "cbaebabacd", p = "abc"
Expected: [0, 6]
Sample 2
Input: s = "abab", p = "ab"
Expected: [0, 1, 2]
Sample 3
Input: s = "aa", p = "bb"
Expected: []
Your solution
Learning objective
Maintain fixed-size window frequencies and compare Counter objects for constant-alphabet anagram checks.