Algorithmssliding window fixed
Sliding Window Fixed (Processing Subarrays of Fixed Size Efficiently)
TT
Testlaa Team
May 14, 2026•1 min read
Fixed-size windows always span exactly k elements. Once the first k sum (or hash) is built, each step adds the entering element and subtracts the leaving element in O(1).
Why this shows up in the real world
Rolling weather averages (last 24 hours), moving averages on stocks, and sensor smoothing all use fixed windows. Games may evaluate the last N damage ticks for combo meters.
Core idea (explained for students)
Initialize window on nums[0:k-1] then extend, or compute full first window then slide: window_sum = window_sum + nums[i] - nums[i-k]. For strings, slide similarly with character counts or bitmasks.
Try this in Python
def max_avg_subarray(nums: list[int], k: int) -> float:
s = sum(nums[:k])
best = s
for i in range(k, len(nums)):
s += nums[i] - nums[i - k]
best = max(best, s)
return best / k
print(max_avg_subarray([1, 12, -5, -6, 50, 3], 4))
Common mistakes
- Using
k > len(nums)without guarding. - Integer overflow in languages without big integers—use modulo if the problem requires it.
- Re-summing the whole window each slide—defeats the purpose.
Key takeaways
- Fixed window = enter/leave bookkeeping.
- Same skeleton for max, min (use deques for min in O(n) total), or averages.
Tags:
Sliding windowPythonStudents
