Free beta: 30 days of full access, no card needed.Sign up free

We use necessary cookies to run the site (sign-in and language). The contact and bug-report forms also use Google reCAPTCHA for spam protection, loaded only if you accept. Privacy policy

Field manual

Sliding window (fixed size)

O(n)

Keep a window of exactly k elements and roll it one step at a time: add the entering element, drop the leaving one, and update the running answer without rescanning the whole window.

Signals

contiguous subarray/substring of a given length kevery window of size krolling average or moving summin/max/count/sum over each fixed span

Template

function windowStat(arr, k) {
    let windowSum = 0;
    for (let i = 0; i < k; i++) windowSum += arr[i];
    let best = windowSum;
    for (let i = k; i < arr.length; i++) {
        windowSum += arr[i] - arr[i - k];
        best = Math.max(best, windowSum);
    }
    return best;
}

Looks similar, isn't

  • Variable sliding window: A fixed window is exactly size k for the whole pass and never grows or shrinks. A variable window has no fixed k; it grows and shrinks itself based on whether a condition holds.
  • Prefix sums: Prefix sums precompute once so ANY arbitrary range can be answered later in O(1). A fixed window rolls a single span of size k forward and only ever answers about that one moving span.

n up to 1e5..1e6 -> O(n): each element enters and leaves the window exactly once, so the roll is one linear pass, not O(nk) of rescanning.

Learn this pattern