Code Snippets
/

Python Sliding Window Template

Python Sliding Window Template

The sliding-window pattern walks two indices forward through a sequence, maintaining an aggregate (sum, count, set, dict) of the current window. It turns 'best subarray of length K' and 'longest subarray with property P' problems into single O(n) sweeps. This entry covers the fixed-size variant, the variable-size shrink-when-invalid variant, and the longest-substring-without-repeats classic.

Python
Easy
3 snippets
sliding-window
algorithms
code-template
py-standard-library

1,181 views

5

def max_sum_window(nums, k):
    """Maximum sum of any contiguous subarray of length k."""
    if k <= 0 or k > len(nums):
        return 0
    window = sum(nums[:k])
    best = window
    for i in range(k, len(nums)):
        window += nums[i] - nums[i - k]   # add new tail, drop old head
        if window > best:
            best = window
    return best

print(max_sum_window([2, 1, 5, 1, 3, 2], 3))   # 9   (5 + 1 + 3)
print(max_sum_window([1, 2, 3, 4, 5], 1))      # 5   (single max)
print(max_sum_window([1, 2, 3, 4, 5], 5))      # 15  (whole array)
print(max_sum_window([5, 5, 5, 5], 2))         # 10  (all equal)
print(max_sum_window([], 3))                    # 0   (empty input)
print(max_sum_window([1, 2], 5))               # 0   (k > n)

For a fixed-size window the trick is to compute the first window in O(k), then slide one position at a time by adding the new right-hand element and subtracting the one that fell off the left. The running sum stays correct without re-summing K elements per step, which drops the runtime from O(n*k) to O(n). The same shape works for any aggregate that can be updated incrementally: count of true values, max via a monotonic deque, or a Counter for character frequencies. Always handle k > n and empty inputs explicitly.