Sliding Window (Efficiently Processing Continuous Subarrays and Substrings)
A sliding window is a contiguous segment [left, right] that moves along an array or string while you maintain aggregates (sum, counts, uniqueness) in amortized constant or linear time—far better than recomputing from scratch each step.
Why this shows up in the real world
Network throughput graphs smooth live traffic with rolling windows. Video buffers keep the last N frames decoded. Retail “last 7 days sales” dashboards slide a date window daily. DNA motif scanners slide k-mers along genomes. The pattern is universal: local neighborhood of fixed interest moving over ordered data.
Core idea (explained for students)
Use two indices L and R. Grow R to include new elements; shrink L when the window becomes invalid or to search for a better answer. Update your aggregate incrementally when L or R moves (for example adjust a running sum or Counter). The window “slides” because you rarely reset both ends to zero simultaneously.
Try this in Python
def max_sum_subarray_k(nums: list[int], k: int) -> int:
if k <= 0 or k > len(nums):
return 0
s = sum(nums[:k])
best = s
for i in range(k, len(nums)):
s += nums[i] - nums[i - k]
best = max(best, s)
return best
print(max_sum_subarray_k([2, 1, 5, 1, 3, 2], 3))
Common mistakes
- Moving
Rwithout updating state, then movingL—double application bugs. - Off-by-one on empty window after shrink loops.
- Confusing sliding window with unrelated two-pointer meet-in-middle setups.
Key takeaways
- Window = interval + incremental state.
- Draw the array with a bracket under
[L,R]before coding. - Ask: fixed length or validity predicate?
