Sliding Window Pattern
The Sliding Window technique is used to find a subarray or substring that satisfies a specific condition. Instead of recalculating everything for each window, we efficiently update the window by adding one element and removing another.
When to Use This Pattern
- Problems involving contiguous subarrays or substrings
- Finding maximum/minimum sum of subarray of fixed size
- Finding longest/shortest subarray with certain properties
- Problems with "substring" or "subarray" keywords
- When you need to maintain a window of elements
Key Concepts
There are two main types of sliding windows:
Visual Representation
Sliding Window - Fixed Size (k=3)
Efficiency: Each window update is O(1) instead of O(k), making the overall algorithm O(n) instead of O(nk)
1. Fixed Size Window
The window size remains constant. We slide it by removing one element from the left and adding one to the right.
window_sum = sum of first k elements
max_sum = window_sum
for i from k to n-1:
window_sum = window_sum - arr[i-k] + arr[i]
max_sum = max(max_sum, window_sum)
2. Variable Size Window
The window size changes based on conditions. We expand the window when we need more elements and shrink it when we have enough.
left = 0
for right from 0 to n-1:
# Expand window
add arr[right] to window
# Shrink window while condition is met
while condition is satisfied:
# Process current window
update result
# Remove left element
remove arr[left] from window
left += 1
Visual Simulation: Fixed Size Window
Finding maximum sum of subarray of size k = 3 in [2, 1, 5, 1, 3, 2]:
Array: [2, 1, 5, 1, 3, 2], k = 3
Window 1 (indices 0-2):
Elements: [2, 1, 5], sum = 8
max_sum = 8
Window 2 (indices 1-3):
Remove 2, add 1: sum = 8 - 2 + 1 = 7
Elements: [1, 5, 1], max_sum = max(8, 7) = 8
Window 3 (indices 2-4):
Remove 1, add 3: sum = 7 - 1 + 3 = 9
Elements: [5, 1, 3], max_sum = max(8, 9) = 9
Window 4 (indices 3-5):
Remove 5, add 2: sum = 9 - 5 + 2 = 6
Elements: [1, 3, 2], max_sum = max(9, 6) = 9
Result: 9