The core idea
Most substring and subarray problems ask you to find the longest, shortest, or count of subarrays satisfying some condition. The naive approach is O(n²): for every starting index, try every ending index. The sliding window keeps a "window" of elements and expands or shrinks it based on the constraint — each element enters and exits the window at most once, giving O(n).
Two window types
Fixed-size windows (find max sum of subarray of size k) and variable-size windows (find the longest substring without repeating characters). Fixed windows are simpler: slide one step at a time, adding the new element and subtracting the one that fell off. Variable windows need two pointers — expand the right pointer until the constraint is violated, then shrink the left until it is satisfied again.
The recognition signal
If a problem asks about a contiguous subarray or substring and involves max/min/count with some constraint on the elements inside that range, reach for sliding window first. Common keywords: "longest", "smallest subarray", "at most k distinct", "minimum window containing".
Common mistakes to avoid
The most frequent bug is forgetting to remove the left element's contribution to window state when shrinking. For example, if you track character frequencies, decrement the count for arr[left] before advancing left. A second bug is using a fixed-size loop when the window should be variable — check the problem constraints carefully.