Sliding window: fixed size

The sliding window: fixed size

Many problems ask about every contiguous window of a sequence — every block of k consecutive elements, every substring of a given length. The naive approach recomputes each window from scratch (O(n·k)). The sliding window technique reuses the previous window's work to get O(n).

The idea

Picture a window of width k sliding along the array. When it moves one step right, it gains one element on the right and loses one on the left. Instead of re-summing all k elements, just update:

windowSum += nums[right]   // element entering
windowSum -= nums[left]    // element leaving

The recipe (fixed size k)

sum = 0
for i in 0..k-1:              // build the first window
    sum += nums[i]
best = sum
for right in k..length(nums)-1:
    sum += nums[right]        // add entering element
    sum -= nums[right - k]    // remove leaving element
    if sum > best:
        best = sum
return best

The same skeleton works whether you track a sum, a product, or character counts in a map — the window just carries whatever summary the problem needs, updated by add/remove as it slides.

Cost

Each element enters and leaves the window exactly once, so the whole scan is O(n), not O(n·k). The window's summary is O(1) (a number) or O(k) (a count map). This is the go-to pattern whenever you hear "of size k" or "of length k."