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.