Visualize the Sliding Window technique for finding the maximum sum subarray of size k. Watch the window glide across the array in O(N) time.
The Sliding Window technique efficiently finds the maximum sum contiguous subarray of a fixed size k by avoiding redundant recomputation. Instead of re-summing k elements each time, you slide the window in O(1) by subtracting the element that left and adding the one that entered.
Start by summing the first k elements. This is your initial window and initial maxSum.
Move one step right: subtract the element leaving the left, add the new element entering the right. Sum updates in O(1), no loop needed.
After each slide, compare the new sum with maxSum. When you find a better window, record it.
Recomputing the sum of every k-subarray from scratch costs O(N·k). The sliding window reduces this to O(N) by reusing the previous sum.
The Sliding Window pattern extends beyond fixed-size windows. Dynamic variants shrink/expand the window based on a condition, making it the go-to technique for subarray/substring problems on LeetCode.