Find All Anagrams in a String
Given two strings s and p Return a list of all starting indices where a substring of s is an anagram of p Example: s = "cbaebabacd", p = "abc" => [0, 6] Example: s = "abab", p = "ab" => [0, 1, 2]
Find All Anagrams in a String is the sliding window pattern: grow, shrink, and maintain just enough state to stay linear. Interviewers love it because it reveals your stateful scanning and your edge-case discipline. The trap is updating window state in the wrong order when you expand or shrink.
Examples
You write
find_anagrams(s: str, p: str)
Example 1
- Input
- s = "cbaebabacd", p = "abc"
- returns
- [0, 6]
Example 2
- Input
- s = "abab", p = "ab"
- returns
- [0, 1, 2]
The pattern behind it
Arrays & Hashing
I reach for it when
- You catch yourself scanning the array again for every element.
- The problem asks about duplicates, pairs, counts or groups.
Say this before you type. Say what the key is and what the value remembers, before you write the loop.
All 127 Arrays & Hashing problemsStrings
I reach for it when
- The input is text and the answer is a count, a substring or a new string.
- You need to compare, reverse or rebuild characters.
Say this before you type. Say which array pattern the string is hiding before you touch a character.
All 51 Strings problems
Meet Coco
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.
Each locked part opens in the editor once the part before it passes.