Technique · Python DSA
Mastering
Sliding Window
in Python
A powerful pattern to optimise problems involving subarrays and substrings — without nested loops.
What is Sliding Window?
Sliding window is a technique where we maintain a window (a contiguous subarray) and move it step-by-step instead of recomputing values from scratch on every iteration. The key observation: when you slide the window one position, you only need to account for one element entering and one leaving.
Fixed window — max sum of k elements
The window size stays constant. Compute the first window sum, then slide by adding the incoming element and subtracting the outgoing one.
def max_sum_subarray(arr, k):
window_sum = sum(arr[:k]) # first window
max_sum = window_sum
for i in range(k, len(arr)):
window_sum += arr[i] # add incoming
window_sum -= arr[i - k] # remove outgoing
max_sum = max(max_sum, window_sum)
return max_sumComplexity: O(n) time, O(1) space. The naive approach (recompute each window from scratch) is O(n·k).
Variable window — longest unique-character substring
Here the window expands with the right pointer, and contracts from the left when a constraint is violated.
def longest_substring(s):
seen = set()
left = 0
max_len = 0
for right in range(len(s)):
while s[right] in seen: # constraint violated
seen.remove(s[left])
left += 1 # shrink from left
seen.add(s[right])
max_len = max(max_len, right - left + 1)
return max_lenCommon patterns
Fixed window (k)
Window size is constant. Typical in max/min sum of k elements.
Variable window
Window expands until a constraint breaks, then contracts.
Substring problems
Use a frequency map inside the window to track character counts.
Min / max window
Deque-based windows give O(n) for maximum-in-sliding-window.
When to use it
- Data is a contiguous subarray or substring
- You need to optimise a nested loop over adjacent elements
- The problem mentions 'maximum / minimum of exactly k elements'
- Constraints on a subarray can be maintained incrementally