Algorithmsfixed window sum

Fixed Window Sum Optimization

TT
Testlaa Team
May 14, 20261 min read

Fixed window sum optimization is the canonical “add new, remove old” trick. It extends to weighted sums, XOR windows (where subtraction is XOR), and modulo sums.

Why this shows up in the real world

Electricity meters over 15-minute buckets can slide additive windows for peak demand charges. GPU tile convolution inner loops reuse partial sums along rows.

Core idea (explained for students)

Maintain current. On slide: current += a[R] - a[L-1] (careful with indices). For max sum of length k you track current and best. For “sum equals target” with length k, compare current to target.

Try this in Python

def num_subarrays_sum_k_len(nums: list[int], k: int, target: int) -> int:
    cnt = 0
    s = sum(nums[:k])
    if s == target:
        cnt += 1
    for i in range(k, len(nums)):
        s += nums[i] - nums[i - k]
        if s == target:
            cnt += 1
    return cnt


print(num_subarrays_sum_k_len([1, 2, 1, 2, 1], 3, 4))

Common mistakes

  • XOR windows: subtraction is not XOR inverse unless you XOR out the leaving bit pattern correctly.
  • Floating sums: prefer exact rational or integer scaling.

Key takeaways

  • Window sum is the hello world of sliding windows.
  • Deque variant arrives when you need min inside window, not sum.

Tags:

Sliding windowPythonStudents