← Lessons

quiz vs the machine

Silver1040

Algorithms

The Sliding Window Pattern

Reuse work across overlapping subarrays by sliding a window instead of recomputing.

4 min read · intro · beat Silver to climb

The wasted recomputation

Many problems ask about every contiguous subarray or substring of a given size, or about the longest run that satisfies a rule. The naive approach reexamines every element of every window from scratch, so the same numbers get added and compared again and again. The sliding window pattern removes that waste.

How the window moves

Keep two boundaries, a left edge and a right edge, that mark the current window over the array.

  • Expand the window by advancing the right edge and updating a running summary such as a sum or a character count.
  • When the window breaks the rule, shrink it by advancing the left edge and undoing that element from the summary.
  • Record the best answer whenever the window is valid.

Each element enters once when the right edge passes it and leaves once when the left edge passes it, so the whole scan touches every item a constant number of times.

Fixed and variable windows

A fixed window keeps a constant size and slides as one block. A variable window grows and shrinks to stay valid, which suits longest or shortest substring questions.

Key idea

Slide a left and right boundary across the data, updating a running summary incrementally so each element is added and removed only once.

Check yourself

Answer to earn rating on the learn ladder.

1. Why is sliding window faster than recomputing each subarray?

2. What distinguishes a variable window from a fixed window?

3. When the window violates its constraint, what should you do?