Loading TechCookies contentβ¦
Sliding window solves: find the optimal contiguous subarray/substring satisfying some constraint.
Brute force generates every subarray: O(nΒ²) or O(nΒ³). Sliding window maintains a dynamic range [left, right] that expands right, then shrinks left β always processing each element at most twice: O(n).
Two variants:
Fixed size window β window size k is given. Slide the window right, add the new element, drop the leftmost.
Variable size window β expand right until the constraint is violated, then shrink left until valid again.
The signal:
One word matters above all: contiguous. If the problem says "subsequence" (elements may be skipped), a window won't work β windows only ever cover an unbroken range.