Sliding Windows: Fixed Size or Variable Size?

← Back to Blog & Articles

A sliding window reuses information about a contiguous range instead of recomputing that range after every move. The first decision is whether the window size is fixed or controlled by a condition.

Fixed-size windows

Use a fixed window when every candidate contains exactly k items: the largest sum of k values, a k-day moving average, or the most frequent symbol in a substring of length k. Add the entering item, remove the leaving item, and update the answer.

Variable-size windows

Use a variable window when the prompt asks for the shortest or longest range satisfying a rule. Expand the right edge to gather information, then move the left edge while the condition remains valid or must be repaired. This works best when the condition changes monotonically as the window grows or shrinks.

Know when it does not fit

A window is not automatically valid for every substring problem. Negative numbers can break sum-based monotonicity, and a requirement involving arbitrary rearrangement may need a different structure. Define the stored state, the validity test, and the exact moment the answer is recorded before coding.

Continue with the book

Explore the full treatment, worked examples, and exercises in Algorithmic Edge.


Adapted from Algorithmic Edge, published by Choral Software. Article text and original examples © 2026 Choral Software. All rights reserved.

Scroll to Top