Fixed Size Window

Template

Use this when every candidate window must have exactly size k.

for r = 0; r < n; r++:
    add nums[r]
 
    if r - l + 1 > k:
        remove nums[l]
        l++
 
    if r - l + 1 == k:
        update answer

Problems Using This Pattern

Maximum Average Subarray I

Problem: find the maximum sum or average over every subarray of size k.

State: maintain window_sum.

Find All Anagrams in a String

Problem: find every start index where a size-len(p) window has the same char counts as p.

State: maintain window_freq and compare against need_freq.

Permutation in String

Problem: check if any size-len(s1) window in s2 is a permutation of s1.

State: same as anagrams, but return boolean.

Number of Sub-arrays of Size K and Average Greater Than or Equal to Threshold

Problem: count size-k subarrays whose average is at least threshold.

State: maintain window_sum; compare against k * threshold.