easySliding WindowSliding Window

Find All Anagrams in a String

easyTime: O(n)Space: O(1)

Signals to notice

find all starting indices where an anagram of p exists in sfixed-size substring matchingcharacter frequency comparison

Brute force first

For each position in s, extract a substring of length p and sort both to compare. The redundancy is that you're re-sorting from scratch at every position instead of updating incrementally. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

The key insight

Slide a window of exactly len(p) over s, maintaining a frequency map. When the window's character counts match p's counts, record the index. Each slide adds one character and removes one — total. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

What must stay true

The window always contains exactly len(p) characters. If its frequency map equals p's frequency map, we've found an anagram. The window never grows or shrinks beyond this size. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Easy way to go wrong

Comparing entire frequency maps at every position is per step — still fast, but the smarter approach tracks a 'matches' counter that updates in. The real trap is forgetting that the window is fixed-size, not variable. The fix is usually to return to the meaning of each move, not just the steps themselves.

Sliding Window Pattern