Sliding Window
Reuse the work from one consecutive group when moving to the next.
sliding window, consecutive, sum, arrayA frame moving across cards
Place a three-card frame over a row. To move it one position right, one card leaves the frame and another enters. You can update the total instead of adding all three cards again.
A sliding window is a consecutive part of a sequence whose boundaries move. This example keeps its size fixed; other problems change the size and need different rules.
Why use it and where it helps
Windows help answer questions about neighbouring items, such as the largest total in any three consecutive days. They are useful when a result can be updated cheaply as the boundaries move. Not every property can be updated by simply subtracting the departing item.
Follow an example
Find the largest sum of two consecutive values in [3, -1, 4, 2].
| Window | Sum | Best so far |
|---|---|---|
[3, -1] | 2 | 2 |
[-1, 4] | 3 | 3 |
[4, 2] | 6 | 6 |
For the second window, subtract the departing 3 and add the arriving 4:
2 - 3 + 4 = 3.
See the reasoning
Follow the example one step at a time
Find the largest sum of two consecutive values. This is a prepared teaching demonstration, not live code execution.
Start with the first window
[3, -1] 4 2 sum: 2 best: 2
The brackets show the two values in the window.
Python illustration
def max_window_sum(numbers, size):
if size < 1 or size > len(numbers):
raise ValueError("size must fit the non-empty window")
current = sum(numbers[:size])
best = current
for right in range(size, len(numbers)):
current += numbers[right] - numbers[right - size]
best = max(best, current)
return best
print(max_window_sum([3, -1, 4, 2], 2))
print(max_window_sum([-5, -2, -3], 2))
Prepared output — not live execution:
6
-5
The function expects an integer window size and raises ValueError if it is
less than one or does not fit. For all-negative inputs it starts with the
first real window, not zero. It returns the sum, not the window's position.
Time, space, and common mistakes
With n input items, initialising and sliding take O(n) time. This Python
example copies the first window for sum, using O(size) extra space; summing
by index could avoid that copy. Variable-sized windows require extra care:
rules that rely on sums only increasing as the right edge moves do not work
with arbitrary negative numbers.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
