Learn

Sliding window pattern explained

A sliding window keeps a stretch of the array that satisfies a rule, then moves the stretch forward instead of starting over.

You grow the right edge one element at a time. When the stretch breaks the rule, you move the left edge forward until it holds again. Each element enters once and leaves once, so the scan is linear.

It shows up in longest-substring problems and in minimum-length subarrays. The pattern is the same: two pointers, a running state, and a rule for when the window is valid.

Practice it by stating the window rule before you write the loop. Then check the empty array and a window that covers the whole input.

Capture a practice problem and ChaiComet explains the approach, the code and the complexity. 20 free credits, no card.

Try free

Sliding window · Two Sum, three ways