Find All Anagrams in a String solution explained
To find every place where a rearrangement of a short pattern starts inside a longer text, slide a window exactly as wide as the pattern across the text, keep letter counts for the window, and update them by one letter in and one letter out per step. Whenever the window's counts equal the pattern's counts, record the window's left index. That gives O(n) time for a fixed alphabet, compared with O(n × m log m) for sorting every window.
By Evin JohnPublished 8 min read
The problem, in plain terms
You get two strings: a text and a shorter pattern. An anagram of the pattern is any string that uses the same characters the same number of times, in any order. Return the list of positions in the text where a substring of the pattern's length begins and that substring is an anagram of the pattern. Windows may overlap, so one letter of the text can belong to several answers.
text = "stopspotpots", pattern = "tops"
index 0 "stop" yes
index 1 "tops" yes
index 4 "spot" yes
index 8 "pots" yes
answer: [0, 1, 4, 8]
text = "reedeer", pattern = "eer"
"ree" at 0 and "eer" at 4 match; "eed", "ede", "dee" do not
answer: [0, 4]Before coding, ask which characters can appear (lowercase English letters, any ASCII, or full Unicode), whether uppercase and lowercase count as the same letter, what to return for an empty pattern, and whether the answer must be in increasing order. Scanning left to right gives increasing order for free.
Why interviewers like this one
It is the cleanest test of the fixed-width window. A variable window grows and shrinks around a condition; here the width is known in advance, so the whole question is whether you can maintain state incrementally instead of recomputing it. Interviewers also listen for how you compare two count tables, because a full comparison on every step is fine for 26 letters but wasteful for a large alphabet, and the tally trick below is the natural improvement to discuss.
A slower starting idea: sort or count every window
The direct approach looks at each of the n - m + 1 windows separately. Sort the pattern once, then sort each window and compare the two sorted strings. That costs O(m log m) per window, so O(n × m log m) overall. Counting each window from scratch instead of sorting it brings each check to O(m), which is O(n × m) in total. Both are correct and both repeat work, because neighboring windows share m - 1 characters. Saying this out loud is the bridge to the real solution: keep the counts and adjust them as the window moves.
The optimal approach: a sliding window of counts
Count the pattern once. Then walk a right pointer across the text. Each new character enters the window, so its count goes up. Once the window is wider than the pattern, the character that falls off the left edge leaves, so its count goes down. As soon as the window is exactly m long, compare the window's counts with the pattern's and, if they match, record right - m + 1. The Python version below assumes lowercase English letters, which is the most common clarification, and uses two 26-slot arrays.
def find_anagrams(text, pattern):
m, n = len(pattern), len(text)
if m == 0 or m > n:
return []
need = [0] * 26
for ch in pattern:
need[ord(ch) - 97] += 1
window = [0] * 26
starts = []
for right in range(n):
window[ord(text[right]) - 97] += 1 # letter enters on the right
if right >= m:
window[ord(text[right - m]) - 97] -= 1 # letter leaves on the left
if right >= m - 1 and window == need:
starts.append(right - m + 1)
return startsWhen the alphabet is open-ended, keep a single map of differences instead: the pattern's count minus the window's count for each character, with any entry that reaches zero deleted. The window is an anagram exactly when the map is empty, so the check is O(1) no matter how many distinct characters exist. This is the mismatch-tally idea in its tidiest form, since the map's size is the number of characters that are still out of balance.
function findAnagrams(text, pattern) {
const m = pattern.length;
const starts = [];
if (m === 0 || m > text.length) return starts;
const diff = new Map(); // pattern count minus window count, zeros removed
const bump = (ch, delta) => {
const next = (diff.get(ch) || 0) + delta;
if (next === 0) diff.delete(ch);
else diff.set(ch, next);
};
for (let i = 0; i < m; i++) bump(pattern[i], 1);
for (let right = 0; right < text.length; right++) {
bump(text[right], -1); // enters the window
if (right >= m) bump(text[right - m], 1); // leaves the window
if (right >= m - 1 && diff.size === 0) starts.push(right - m + 1);
}
return starts;
}Both loops index the strings by position on purpose. In JavaScript, iterating a string with for...of walks Unicode code points while text[i] walks UTF-16 units, and mixing the two would make the counts disagree on emoji and some rare characters. If the problem truly needs code points, convert both strings with Array.from first and index the arrays.
Complexity summary
| Approach | Time | Extra space |
|---|---|---|
| Sort every window and compare | O(n × m log m) | O(m) for the sorted copy |
| Count every window from scratch | O(n × m) | O(k) |
| Sliding window, compare two count arrays | O(n × k), which is O(n) for 26 letters | O(k) |
| Sliding window with a difference map | O(n + m) | O(number of distinct characters) |
The output list itself can hold up to n - m + 1 indexes, for example when the text and pattern are both made of a single repeated letter, so it is fair to mention that the answer's size is not counted in the extra space above.
Edge cases to test
- Pattern longer than the text: return an empty list without touching the arrays.
- Empty pattern or empty text: agree on the convention first; the code above returns an empty list.
- Every window matching, such as text "aaaa" with pattern "aa", which should give [0, 1, 2].
- A match at the very end of the text, which catches loops that stop one step early.
- Characters that appear in the text but not in the pattern, which must still be counted and removed correctly.
- Mixed case or punctuation, if the clarification allowed them (the Python array version does not).
Mistakes that cost points
- Recording a match before the window is full, which reports false starts in the first m - 1 steps.
- Removing text[right - m + 1] instead of text[right - m], which shrinks the window to m - 1.
- Using ord(ch) - 97 on input that may contain capitals or symbols. In Python, capitals from G onward produce negative indexes that silently wrap to other letters' slots, so the bug can give wrong answers instead of an error.
- Leaving zero entries in a difference map and then checking its size, which never reaches zero.
- Sorting each window and calling it linear, which an interviewer will catch when you state the complexity.
How to explain it out loud
Fictional example
- Candidate
- Every candidate substring has the pattern's length, so I'll keep one window of exactly that width and slide it one step at a time. Two windows next to each other differ by one letter in and one letter out.
- Candidate
- I'll keep letter counts for the window. On each step I add the new right letter, and once the window is too wide I subtract the letter that just left. When the window is full and its counts equal the pattern's, I record the left index.
- Candidate
- With 26 letters the comparison is constant, so the whole scan is linear. If the alphabet were large, I'd track only the difference between the two count tables and check whether it's empty.
Common follow-ups
- Return only whether any anagram exists: stop at the first match instead of collecting all of them.
- Return the matching substrings rather than their indexes: slice the text at each recorded start.
- Ignore case and spaces: normalize both strings before counting, and mention that normalization changes indexes if you remove characters.
- Stream the text one character at a time: the window only needs the last m characters, so a queue of length m replaces random access into the text.
Related problems
Counting with a hash table is also the core of Intersection of Two Arrays, where two inputs are compared by their values rather than their order. For a different use of two indexes moving through one array, see how Remove Duplicates from Sorted Array keeps a read pointer and a write pointer.
Using Natively while you practice
Sliding window bugs are usually off-by-one bugs, and they are easier to find with a second pair of eyes. In practice sessions on Mac or Windows, Natively can take a screenshot of the prompt, suggest the window setup, and look over a failing run with you. It also transcribes what you say, so afterward you can check whether you explained when the window becomes full before you wrote the check. More on AI help for LeetCode-style practice.
Questions people ask
How do you solve Find All Anagrams in a String?
Slide a window as wide as the pattern across the text, adding the letter that enters and removing the letter that leaves at each step. When the window's letter counts equal the pattern's, record the window's start index.
What is the time complexity of Find All Anagrams in a String?
O(n) for a fixed alphabet such as 26 lowercase letters, because each step changes two counts and compares a constant-size table. Extra space is O(1) for the counts, not counting the output list.
Is this a sliding window problem?
Yes, a fixed-size one. The window width always equals the pattern length, so the window moves but never grows or shrinks.
How do you compare the counts quickly for a large alphabet?
Keep one map of differences between the pattern's counts and the window's counts, deleting entries that reach zero. The window is an anagram exactly when that map is empty.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
