DSA AnimatorDSA animations
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
—
r
—
matches
0
found
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.

How to solve Find All Anagrams in a String

LeetCode 438 · Medium · Strings · Pattern: Fixed Sliding Window

Why the obvious approach is slow

Taking three letters at every index and sorting them repeats the same work again and again. If p is long, that becomes very slow.

The key idea

Keep a fixed window, as long as p. Count the letters of p once. Each time the window slides one step, one letter comes in, and one letter goes out. Update just those two counts, and check whether the counts match.

Remember

Anagram windows are fixed windows with matching counts. Update two counts per step instead of recounting.

Run the animation above on your own input, or watch the 1:40 video explanation of Find All Anagrams in a String with a dry run and Java code.

More Strings problems