Sliding Window Technique with Examples
2 March 2026•2 min read
What Is Sliding Window?
Instead of checking every subarray (O(n²)), maintain a "window" and slide it while updating a running result. Often O(n).
Fixed-Size Window
Window size is given (e.g. K). For each new element, add it; if window size > K, remove from the other end.
Examples
- Max sum of any subarray of size K.
- First negative in every window of size K.
- Maximum in every window of size K (use deque for O(n)).
Variable-Size Window
Window grows and shrinks based on a condition (e.g. "longest subarray with sum ≤ K").
Examples
- Longest substring with at most K distinct characters.
- Minimum size subarray with sum ≥ target.
- Longest substring without repeating characters.
Implementation Tips
- Use two pointers
leftandright(orstartandend). - Use a hash map or variables to track window state.
- Expand
right, then shrinkleftwhen the window becomes invalid.
Summary
If the problem asks for a subarray or substring satisfying a condition, think sliding window. Practice on Preplume(/) to build intuition.