Sliding Window
Maintains a contiguous subarray (window) of variable or fixed size, expanding/shrinking from both ends to efficiently compute properties like maximum sum or longest valid substring.
Syntax
slidingWindow(arr, k) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
arr | Array<any> | Yes | The input array or string to apply the window over. |
k | number | No | Window size for fixed-size variants. Omit for variable-size windows. |
Returns
any — Depends on variant: maximum subarray sum, longest valid substring length, etc.
Examples
// Fixed window: max sum of k consecutive elements
function maxSumWindow(arr, k) {
let windowSum = arr.slice(0, k).reduce((a, b) => a + b, 0);
let maxSum = windowSum;
for (let i = k; i < arr.length; i++) {
windowSum += arr[i] - arr[i - k];
maxSum = Math.max(maxSum, windowSum);
}
return maxSum;
}
console.log(maxSumWindow([2, 1, 5, 1, 3, 2], 3));
Output
9
// Variable window: longest substring with at most k distinct characters
function longestSubstringKDistinct(s, k) {
const freq = new Map();
let left = 0, maxLen = 0;
for (let right = 0; right < s.length; right++) {
freq.set(s[right], (freq.get(s[right]) ?? 0) + 1);
while (freq.size > k) {
const c = s[left++];
if (freq.get(c) === 1) freq.delete(c);
else freq.set(c, freq.get(c) - 1);
}
maxLen = Math.max(maxLen, right - left + 1);
}
return maxLen;
}
console.log(longestSubstringKDistinct('araaci', 2));
Output
4
Notes
| Case | Time | Space |
|---------|------|-------|
| Best | O(n) | O(1) |
| Average | O(n) | O(k) |
| Worst | O(n) | O(k) |
The sliding window technique reduces an O(n²) brute-force over all
subarrays to O(n) by avoiding redundant recomputation. Two pointers
(left and right) define the window. In the fixed-size variant, add the
new element and subtract the outgoing element. In the variable-size
variant, expand by moving right and shrink by moving left until the
window satisfies the constraint. A monotonic deque (deque maintaining
max/min) extends this to find the max/min in each window in O(n) total.