Types of Sliding Windows
1. Fixed-size Sliding Window
You know the window size (say k), and the goal is to perform operations over every subarray of size k.
Common Example:
Find the maximum sum of any subarray of size k.
Pseudocode
class SlidingWindowFixed {
function maxSum(arr, k):
n = length(arr)
windowSum = sum of first k elements
maxSum = windowSum
for i = k to n-1:
windowSum = windowSum + arr[i] - arr[i - k]
maxSum = max(maxSum, windowSum)
return maxSum
}
Time and Space Complexity
- Time Complexity: O(n)
- Space Complexity: O(1)
2. Variable-size Sliding Window
Window size changes dynamically based on the conditions. You expand the window by moving the right pointer and shrink it by moving the left pointer until conditions are satisfied.
Common Example:
Find the length of the longest substring with at most K distinct characters.
Pseudocode
class SlidingWindowVariable {
function longestSubstringWithKDistinct(s, k):
left = 0
right = 0
freqMap = {}
maxLen = 0
while right < length(s):
add s[right] to freqMap
while size of freqMap > k:
decrement freqMap[s[left]]
if freqMap[s[left]] == 0:
remove s[left] from freqMap
left += 1
maxLen = max(maxLen, right - left + 1)
right += 1
return maxLen
}
Time and Space Complexity
- Time Complexity: O(n)
- Space Complexity: O(k) — for hash map