Back to DSA track
DSA Topic

Sliding Window

A moving-interval framework for subarray and substring problems where the real work is maintaining just enough state as the window expands and contracts.

Keeps interval problems linear by having each element enter and leave once
Becomes mechanical once window validity is defined clearly
Most bugs come from updating the answer before the window is valid

How to think about it

Sliding window is the pattern to reach for when the answer depends on a contiguous range rather than on isolated elements. Instead of recalculating every interval from scratch, you carry forward the state that tells you whether the current window is useful.

The pattern feels tricky at first because the interval changes size while your bookkeeping changes with it. Once you define what the window means and what makes it valid, the implementation usually becomes steady and predictable.

Signals that the pattern fits

  • The problem asks about a subarray, substring, or contiguous interval.
  • You can describe window validity with a running sum, counts, or a compact state object.
  • The interval either stays fixed at size k or grows until a condition breaks.
  • Each element should only need to enter and leave the interval once.

Movement models

Fixed-size windows

Keep the interval length constant and update the running state as one item leaves and another enters.

  • Ideal for average, max, or count questions over an exact size k
  • The outgoing and incoming elements are the only state updates each step
  • You almost always update the answer after the new size-k window is formed

Variable-size windows

Grow the right edge, then shrink the left edge until the window becomes valid again.

  • Common in longest unique substring or minimum covering window problems
  • The left pointer only moves when a validity condition breaks
  • Answer updates belong after the shrink loop for valid-window problems

Quick review checklist

  • What state tells you whether the current window is valid?
  • What event forces the left edge to move?
  • When should the answer update: before shrinking or after it?
  • Can you explain the window length formula right - left + 1 without hesitation?