← Back to DSA Animator
Find All Anagrams in a String LC #438 Medium Fixed Sliding Window · Matches Counter
Problem

Given strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.

Example
Input: s = "cbaebabacd", p = "abc"
Output: [0, 6]
Explanation: "cba" at index 0 and "bac" at index 6 are anagrams of "abc".
Constraints: 1 ≤ s.length, p.length ≤ 3×10⁴  |  s and p consist of lowercase English letters.
Try Examples
Custom:
Approach
Fixed Sliding Window — Collect All Anagram Positions
Same matches-counter as LC567, but don't stop on first match — collect ALL windows where matches == needed. Each slide is O(1). O(n) time, O(1) space.
① Init
② Build Window
③ Slide →
④ Done
Pattern p
String s
matches / needed 0 / 0
Waiting to start…
Char Frequencies — need (p) vs have (window)
charneedhave
Anagram Start Indices 0 found
None found yet…
Init
Press ▶ Play or Next Step to begin.
Variables
L (left)
R (right)
matches
0
found count
0
Step Logic
Press ▶ Play or Next Step to begin.
Ready 0 / 0
Select an example and press Play.
Algorithm
1
Build need map from p. needed = unique chars in p.
2
Slide r over s. Add s[r] to have. If have[c]==need[c] → matches++
3
When r ≥ k: remove s[r−k] from have. If was matching → matches--
4
If matches == needed → record l = r−k+1. Continue scanning (don't stop!)
5
After full scan → return all collected start indices
Time
O(n)
Space
O(1)
Why It Works

Same as LC567 but collect all: An anagram of p must have exactly the same char frequencies in a window of size k = p.length. We check every k-length window and collect all that match.

matches counter trick: Only 2 updates per slide — add right, remove left. Each is O(1). No full array comparison. O(1) per step.

Key difference from LC567: Don't return on first match. After recording l, the window slides naturally to the next position — the loop continues until all of s is scanned.