What is the Sliding Window Pattern?
The Sliding Window pattern maintains a contiguous range of an array or string between two pointers — left and right — together with an aggregate of the range's contents (a sum, a count, or a frequency map). Instead of recomputing the aggregate for every possible subarray (O(n²) or worse), the window updates it incrementally: add one element when the right pointer expands, remove one when the left pointer contracts. Each element enters and leaves at most once, so the total work is O(n).
Fixed vs. Variable Windows
- ●Fixed-size: the window always spans exactly k elements — slide both pointers together (max sum of size k, averages, anagram checks).
- ●Variable-size: grow until a condition breaks, then shrink until it holds again (smallest subarray ≥ target, longest substring without repeats).
- ●Recognize it: the problem asks about a contiguous subarray/substring and some best/count over all of them.
Classic Problems
- ✓LeetCode 3 — Longest Substring Without Repeating Characters
- ✓LeetCode 209 — Minimum Size Subarray Sum
- ✓LeetCode 424 — Longest Repeating Character Replacement
- ✓LeetCode 567 — Permutation in String