How to Compute Sliding Window Sum of Size k in Python
Compute the sum of every contiguous subarray of a fixed size k using an efficient O(n) sliding window technique.
Python code
20 linesdef sliding_window_sum(nums, k):
"""Return a list of sums for each contiguous subarray of size k."""
if not nums or k <= 0 or k > len(nums):
return []
result = []
window_sum = sum(nums[:k])
result.append(window_sum)
for i in range(k, len(nums)):
window_sum += nums[i] - nums[i - k]
result.append(window_sum)
return result
if __name__ == "__main__":
data = [1, 3, 5, 7, 9, 11]
k = 3
print(sliding_window_sum(data, k))
Output
[9, 15, 21, 27]
How it works
This function starts by summing the first k elements to initialize the window. Then, for each step forward, it adds the new element entering the window and subtracts the element leaving it, maintaining a running sum. This avoids recalculating the entire window sum from scratch each time, reducing time complexity from O(n*k) to O(n). The loop runs from index k to the end, updating the window sum in constant time per iteration. Edge cases like empty lists or invalid k are handled by returning an empty list.
Common mistakes
- Not checking if k exceeds the list length, leading to an empty result or index error.
- Using a naive O(n*k) approach by summing each window separately, which is slower.
- Forgetting to subtract the element that leaves the window, causing incorrect sums.
Variations
- Use itertools.accumulate to compute prefix sums, then derive each window sum as prefix[i+k] - prefix[i].
- Use a list comprehension with slicing: [sum(nums[i:i+k]) for i in range(len(nums)-k+1)].
- For streaming data, implement the window as a deque to add and remove elements.
Real-world use cases
- Calculating moving averages for time-series metrics like server latency.
- Computing rolling sums of transactions for anomaly detection in financial data.
- Aggregating sensor readings over a fixed time window in IoT pipelines.
Sponsored
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.