Python Snippet

Python Sliding Window Template

Difficulty: Easy

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.

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,180 views

5

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.