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.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 13 views 0 copies

Python code

20 lines
Python 3.9+
def 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

stdout
[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

  1. Use itertools.accumulate to compute prefix sums, then derive each window sum as prefix[i+k] - prefix[i].
  2. Use a list comprehension with slicing: [sum(nums[i:i+k]) for i in range(len(nums)-k+1)].
  3. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.