Sliding Window
Signal: a contiguous subarray or substring, plus "longest", "shortest", "at most k", "contains all of", or a fixed window size k.
Core idea: instead of recomputing every window from scratch (O(n·k) or O(n²)), maintain the window's state as you add the element entering on the right and remove the element leaving on the left. Each index enters and leaves once, so the total is O(n).
Two templates
# Variable-size window: longest window satisfying a condition
l = 0
state = ... # counts, sum, set...
for r, x in enumerate(a):
add(x, state) # expand right
while not valid(state): # shrink until valid again
remove(a[l], state); l += 1
best = max(best, r - l + 1)
# Fixed-size window of length k
for r, x in enumerate(a):
add(x)
if r >= k: remove(a[r - k])
if r >= k - 1: record(window)For "shortest window that satisfies X", flip it: expand until valid, then shrink while still valid, recording the minimum each time.
The shrink step relies on monotonicity: shrinking a window must never make an invalid window valid in a way you'd miss. With negative numbers, "subarray sum ≥ k" breaks this. Use prefix sums + a monotonic deque or a hash map instead (see Prefix Sums).