Sliding a Fixed-Length Window
A fixed-length window can update a running total by removing the departing value and adding the incoming one.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace three windows
For values 2, 5, 1, 4 and width two, the first total is seven. Shifting removes two and adds one, giving six. Shifting again removes five and adds four, giving five. Use half-open slice bounds to identify both offsets.
Graduate from recalculation
Computing each total independently can repeat work. The update keeps a loop accumulator representing exactly the active interval. Check widths one and the full length, and state what zero and oversized widths mean.[1]
Update the departing and arriving terms once
On [5, -2, 4, 7, 1], a length-three window starts with sum seven. When it moves one step right it drops five and adds seven, raising the sum to nine. It then drops minus two and adds one, reaching twelve. See loop running totals.
Window sum
[5, -2, 4] 7
[-2, 4, 7] 9
[4, 7, 1] 12
Verify the width and the endpoint policy
A width larger than input may yield no window. A zero width needs an explicit contract if allowed. With floating-point values, repeated addition and subtraction can accumulate rounding differences from recomputing individual windows. Test a negative departing term and the last full window.