mediumSliding WindowSliding Window

Permutation in String

mediumTime: O(n)Space: O(1)

Signals to notice

check if one string is a permutation of a substringthe same-size window keeps movingcharacter frequency match

Brute force first

Check every substring of s1's length in s2. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

The key insight

Slide a window of size len(s1) over s2, maintain frequency counts. 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

A permutation exists when the window's character counts exactly match s1's counts. 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 each step — use a 'matches' counter for updates. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Sliding Window Pattern