Sliding Window
These
17. Pattern: Sliding Window
A sliding window maintains an interval:
Typical structure:
l = 0
for r in range(n):
# add nums[r]
while condition_is_invalid:
# remove nums[l]
l += 1
# process window
If both \(l\) and \(r\) move only forward:
and
Therefore total pointer movement is at most:
giving:
18. Fixed-Size Sliding Window
If the window has fixed size \(k\):
Maintain its sum:
Each step performs constant work.
Therefore:
instead of:
19. Variable-Size Sliding Window
Typical problem:
Find the longest/shortest subarray satisfying some condition.
Structure:
The crucial requirement is that the validity condition should allow the left pointer to move monotonically.
20. Sliding Window Warning
Do not automatically use sliding window just because the problem says "subarray".
Sliding window works when the condition has the right monotonic behavior.
For example, with positive numbers:
increases when \(r\) increases and decreases when \(l\) increases.
This property often makes sliding window possible.
With arbitrary negative numbers, that monotonicity can disappear.