The pattern: sliding window
Maintain a contiguous range of elements that expands and contracts across an array or string, replacing O(n²) subarray scans with a single O(n) pass.
Many problems that ask for the "longest", "shortest", or "optimal" contiguous subarray or substring tempt you to re-scan every window from scratch, leading to O(n²) or O(n³) brute-force solutions. A sliding window moves two boundaries across the sequence, updating running totals or counts in O(1) per step so the entire array is processed in a single O(n) pass.
01The three shapes
1. Fixed-size window. The window size is fixed at k. Build the first window of size k, then slide one position at a time: add the incoming element at the right, drop the exiting element at the left, and update the answer.
for i from 0 to k - 1:
add a[i] to window
for i from k to n - 1:
add a[i] ; drop a[i - k]
update bestUsed for: Maximum Average Subarray I, Permutation in String, Find All Anagrams in a String.
2. Variable-size window (grow right, shrink left). Expand right to include new elements and update window state. When a constraint is violated (or while a target is satisfied), advance left to shrink the window until it becomes valid (or minimal) again.
left = 0
for right from 0 to n - 1:
add a[right] to window
while window violates constraint:
remove a[left] from window
left += 1
update bestUsed for: Longest Substring Without Repeating Characters, Longest Repeating Character Replacement, Fruit Into Baskets, Minimum Window Substring.
3. Difference of at-mosts (atMost(k) - atMost(k - 1)). Directly counting subarrays with "exactly k" of a target item with a single sliding window is tricky because padding (like intervening even numbers) can expand either end without changing the count. Because "at most k" is monotonic, we count subarrays with at most k, count subarrays with at most k - 1, and subtract the two.
exactCount(k) = atMost(k) - atMost(k - 1)Used for: Count Number of Nice Subarrays (and related counting problems like Subarrays with K Different Integers).
02How to spot it
- The problem asks for a contiguous subarray or substring (not a subsequence).
- You are optimizing for maximum length, minimum length, or a running aggregate (sum, average, character counts).
- Neighboring windows overlap heavily: moving by one element adds one item and removes one item, allowing an O(1) state update.
- The condition exhibits monotonicity: expanding the window never decreases the count of elements or sum, and shrinking never increases it.
03Why it's safe and runs in O(n)
A common worry in interview rooms is the while loop inside the for loop: doesn't nested looping mean O(n²)?
The answer is amortized analysis: right advances at most n times, and left advances at most n times over the entire life of the algorithm. Neither pointer ever moves backward. Therefore, the total number of operations across all iterations is at most 2n, keeping time strictly O(n).
04Problems in this chapter
Maximum Average Subarray I, Longest Substring Without Repeating Characters, and Permutation in String are free to start with. Then: Find All Anagrams in a String, Longest Repeating Character Replacement, Fruit Into Baskets, Count Number of Nice Subarrays, and Minimum Window Substring.