← Lessons

quiz vs the machine

Gold1380

Algorithms

The Sliding Window Variable Size

Growing and shrinking a window to find the best span that satisfies a constraint.

5 min read · core · beat Gold to climb

A window that breathes

A variable size sliding window does not have a fixed width. Instead its two ends move independently so the window grows when it can and shrinks when it must, hunting for the longest or shortest span that satisfies some constraint.

Expand then contract

The standard loop drives the right edge forward to include new elements, then conditionally pulls the left edge inward:

  • Expand by moving the right end one step and updating the window state.
  • Contract by moving the left end while the window violates or over satisfies the constraint.
  • Record the best valid window seen so far.

Each end only ever moves forward, so although the window resizes constantly, the total movement is bounded and the scan remains linear.

Choosing the goal

For a longest valid span you usually expand greedily and contract only when the constraint breaks. For a shortest valid span you expand until the constraint is met, then contract aggressively to tighten it.

Key idea

A variable window expands its right edge to include elements and contracts its left edge to restore the constraint, and because both edges only move forward the whole search stays linear.

Check yourself

Answer to earn rating on the learn ladder.

1. What controls when the left edge of a variable window moves?

2. Why is a variable window scan still linear despite constant resizing?

3. For finding the shortest valid span, what is the typical strategy?