Find All Anagrams in a String
Problem Statement
You are given two strings s and p.
An anagram of p is any rearrangement of its letters (same letters, same counts, any order). Find every position in s where a substring that is an anagram of p starts, and return those start indices. The order of the indices does not matter.
Two strings s and p of lowercase English letters.
A list of all start indices i such that s[i … i + p.length − 1] is an anagram of p. Empty if there are none.
"cba" starts at 0 and "bac" starts at 6. Both are rearrangements of "abc".
"ab" at 0, "ba" at 1 and "ab" at 2 are all anagrams of "ab". Matches may overlap.
- • 1 ≤ s.length, p.length ≤ 3 · 10^4
- • s and p contain only lowercase English letters
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For each length-m window, count its letters fresh and compare with p
Two count updates per slide, then a 26-letter comparison
Track how many letters already match; record every window with 26
Every anagram of p has length m. For each start in s, count the letters of s[start … start+m−1] from scratch and compare the 26 counts with p's counts. Record the start when they are equal.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Sliding Window translate into production architectures and low-level memory mechanics.