π§© Python DSA Patterns β Sliding Window πͺπ
Posted on: September 5, 2025
Description:
The sliding window is a powerful algorithmic pattern for solving problems on contiguous arrays & strings.
Instead of recalculating values every time, you slide the window and update results incrementally β turning O(nΒ²) brute force into O(n).
π Fixed-Size Window β Max Sum Subarray of Size k
We keep the sum of the first window of size k, then slide forward step by step: subtract the element going out, add the new one coming in.
def max_sum_subarray_k(arr, k):
window_sum = sum(arr[:k])
max_sum = window_sum
for i in range(k, len(arr)):
window_sum += arr[i] - arr[i-k]
max_sum = max(max_sum, window_sum)
return max_sum
print(max_sum_subarray_k([2, 1, 5, 1, 3, 2], 3)) # Output: 9
π Variable-Size Window β Min Subarray Length β₯ Target
We expand the window until the sum β₯ target, then shrink it from the left to minimize length.
def min_subarray_len_at_least(target, arr):
left = 0
total = 0
best = float("inf")
for right in range(len(arr)):
total += arr[right]
while total >= target:
best = min(best, right - left + 1)
total -= arr[left]
left += 1
return 0 if best == float("inf") else best
print(min_subarray_len_at_least(7, [2, 3, 1, 2, 4, 3])) # Output: 2
β Takeaway
Sliding Window = reuse work from the previous step instead of recalculating.
Use it whenever the problem mentions contiguous subarrays or substrings.
ποΈ Practice Problems
Try applying the Sliding Window pattern to these:
- Maximum Average Subarray I (LeetCode 643)
- Longest Substring Without Repeating Characters (LeetCode 3)
- Minimum Size Subarray Sum (LeetCode 209)
π Full Script
The blog covers the essentials β find the complete notebook with all snippets & extras on GitHub Repo π Python DSA Patterns
No comments yet. Be the first to comment!