Maintain a rolling view of consecutive items rather than recomputing each window.
What You Will Learn
A fixed-length sliding window is useful for moving sums, rolling averages and recent event counts. Add the new rightmost item and subtract the item leaving the window. This reduces repeated summation for overlapping windows, but requires a clear policy for inputs shorter than the window.
Time complexity assumes a specific input structure. Include setup work such as sorting or building a lookup table when comparing complete solutions.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
def rolling_sums(values, window_size):
if window_size < 1 or window_size > len(values):
return []
current = sum(values[:window_size])
results = [current]
for index in range(window_size, len(values)):
current += values[index] - values[index - window_size]
results.append(current)
return results
print(rolling_sums([2, 4, 1, 5, 3], 3))
How the Example Works
- The function rolling_sums defines reusable behavior; its body executes when it is called, not when it is declared.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
For the chosen input, the expression rolling_sums([2, 4, 1, 5, 3], 3) prints [7, 10, 9]. Compare that result with the rule above before you change the argument.
Expected output from the example:
[7, 10, 9]
When You Would Use This
This technique matters when a program handles larger queues, sorted records, or repeated lookups. Choose the data structure based on actual operations and the preconditions the algorithm requires. Verify boundary inputs before optimizing for speed.
Practice: Modify the Code
Compute rolling averages by dividing each rolling sum by the window size.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Recalculating sum(values[i:i+size]) in every step without considering the repeated work.
- Forgetting to remove the element that leaves the window when advancing.
Key Takeaways
- Maintain a rolling view of consecutive items rather than recomputing each window.
- A fixed-length sliding window is useful for moving sums, rolling averages and recent event counts.
- Apply this operation only after checking the assumptions and input conditions shown in the example.