Algorithmsfixed size sliding window

Fixed Size Sliding Window Technique

TT
Testlaa Team
May 14, 20261 min read

This skill emphasizes the mechanics of a length-k window: how to initialize it, how to advance R and L together so width stays k, and how to emit an answer each step.

Why this shows up in the real world

Quality control might inspect every batch of 100 items on a conveyor—inspectors mentally slide a fixed batch window. Audio FFT frames often hop with fixed hop length, overlapping fixed windows.

Core idea (explained for students)

Pattern: for R in range(k-1, n): L = R - k + 1. Alternatively keep R as for-loop index and L = R - k + 1 implicitly. Always ensure L >= 0.

Try this in Python

def all_window_sums(nums: list[int], k: int) -> list[int]:
    if k == 0:
        return []
    s = sum(nums[:k])
    out = [s]
    for i in range(k, len(nums)):
        s += nums[i] - nums[i - k]
        out.append(s)
    return out


print(all_window_sums([1, 2, 3, 4, 5], 2))

Common mistakes

  • One-off errors tying L to R when using 0-based indexing.
  • Processing windows before the first full k elements exist unless the problem allows partial windows.

Key takeaways

  • Tie L and R with the invariant R - L + 1 == k.
  • Print small traces for k=3 on paper.

Tags:

Sliding windowPythonStudents