Mastering Sliding Window Technique in Python
A powerful pattern to optimize problems involving subarrays and substrings.
What is Sliding Window?
Sliding window is a technique where we maintain a window (subarray) and move it step-by-step instead of recomputing values repeatedly.
Why Use It?
- Reduces time complexity
- Avoids nested loops
- Efficient for contiguous subarrays
Fixed Window Example
def max_sum_subarray(arr, k):
window_sum = sum(arr[:k])
max_sum = window_sum
for i in range(k, len(arr)):
window_sum += arr[i]
window_sum -= arr[i - k]
max_sum = max(max_sum, window_sum)
return max_sumVariable Window Example
def longest_substring(s):
seen = set()
left = 0
max_len = 0
for right in range(len(s)):
while s[right] in seen:
seen.remove(s[left])
left += 1
seen.add(s[right])
max_len = max(max_len, right - left + 1)
return max_lenCommon Patterns
- Fixed window size (k)
- Variable window size
- Substring problems
- Maximum / minimum window
When to Use
- Contiguous subarrays
- Strings and substrings
- Optimization problems