Sliding Window
Maintain a window that slides across an array, adding elements on the right and removing on the left. Converts O(n·k) brute-force subarray problems into O(n) by never recomputing from scratch.
What is the sliding window technique?
A sliding window keeps a range [left, right] over an array or string and moves it forward, updating a running result instead of recomputing from scratch. It turns problems like "maximum sum of k consecutive items" or "longest substring without repeating characters" from O(n²) or worse into O(n).
function longestUniqueSubstring(s) { // O(n)
const lastSeen = new Map();
let left = 0, best = 0;
for (let right = 0; right < s.length; right++) {
if (lastSeen.get(s[right]) >= left) left = lastSeen.get(s[right]) + 1; // shrink
lastSeen.set(s[right], right);
best = Math.max(best, right - left + 1);
}
return best;
}
longestUniqueSubstring("abcabcbb"); // 3 ("abc")Fixed Window
Window size k stays constant. Slide one step at a time: add rightmost, remove leftmost. Example: max sum of k elements.
Variable Window
Window shrinks when a constraint is violated, expands when it is satisfied. Example: longest substring without repeat.
Fixed window — animated
// Array state
// Pseudocode
Variable window pseudocode
1// Variable window: longest substring without repeat2function longestUnique(s):3 seen = {} // char → last seen index4 left = 0, maxLen = 05 for right from 0 to len(s) - 1:6 if s[right] in seen and seen[s[right]] >= left:7 left = seen[s[right]] + 1 // shrink left8 seen[s[right]] = right9 maxLen = max(maxLen, right - left + 1)10 return maxLen // O(n)
Minimum window substring — trace it
// Trace output
Click ▶ Run to trace execution
Complexity
Linear time
Linear time
Linear time
Constant time
O(k) time
🎯 Quick Check
What is the time complexity of finding the max sum subarray of size k using the sliding window technique?
Sliding Window: summary
Key points
- Fixed-size windows add the new item and subtract the one that left.
- Variable-size windows expand right, then shrink left while a condition is violated.
- Keep the window's state (sum, counts, last positions) in variables or a hash map.
Frequently asked questions
›Sliding window vs two pointers?
A sliding window is a two-pointer pattern where both pointers move in the same direction and the range between them matters.