🧩 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!