PrepStack · Markdown HTML

Fixed-size sliding window

Pointers and sliding window · HTML

Formal shape

Maintain summary S for [r-k+1,r]. Add a[r], remove a[r-k] once oversized, and query the summary whenever the window length reaches k.

Recognition signals

False friends

SignalWhy it is different
Variable-length longest or shortest segmentWhen validity controls length, use a variable window with repeated shrinking.
Any k selected itemsA sliding window covers contiguous segments, not combinations.

Core invariant

After processing right endpoint r, the summary exactly describes the most recent at most k items; a result is recorded only at length k.

State, transition, and processing order

ItemDefinition
Stateright, implicit left=right-k+1, aggregate such as sum/frequency/match count, and best result.
TransitionAdd the new right item, remove the item k positions behind after the prefix is long enough, then read the mature window.
Frontier / orderA fixed-width contiguous index segment shifting right by one each round.

Python skeleton

def max_fixed_sum(values, k):
    if k <= 0 or k > len(values):
        return None
    window = sum(values[:k])
    best = window
    for right in range(k, len(values)):
        window += values[right]
        window -= values[right - k]
        best = max(best, window)
    return best

Correctness sketch

  1. The initial summary equals the first length-k window.
  2. Subtracting the sole leaver and adding the sole entrant converts one exact window summary into the next.
  3. The loop visits every and only length-k window in right-endpoint order, so the recorded optimum is correct.

Complexity

TimeSpaceParameters
O(n)O(1) or O(Σ)n is length; sums need O(1), while frequency state uses Σ distinct keys in the window or domain.

Edge cases

Error patterns

PatternWhy it fails / fix
Off-by-one leaverA new item at right corresponds to the leaving index right-k.
Scoring immature prefixesThe first k-1 prefixes are not length-k windows.
Re-summing a slice each roundThat regresses to O(nk) and allocates slices.

Selection and exclusion rules

RelationTemplateBoundary
different length policyVariable-size sliding windowValidity dynamically determines length.

Original micro-example

PartDetail
ResultThe maximum fixed-window sum is 7.
SetupValues [2,5,-1,4], k=2.
TraceWindow sums are 7, 4, and 3, each obtained with one add and one subtract.

Recall prompts

My notes