Visualize LeetCode 209 step by step. Watch the variable sliding window expand to accumulate sum and shrink to find the minimum length subarray ≥ target.
About this algorithm
Given an array of positive numbers and a target, find the length of the shortest run of neighbouring values whose sum is at least the target, or 0 if no run reaches it. A window grows until it has enough, then squeezes from the left to see how short it can get.
Use this pattern for "shortest stretch that reaches a goal": the fewest days to save a certain amount, the shortest stretch of road with enough fuel stops. It needs every number to be positive, because then adding a value always raises the sum and removing one always lowers it, which is what lets the window move in one direction only. With negative numbers you need prefix sums and a different method. The max consecutive ones page is the mirror image: it wants the longest window that stays within a limit.
Move right forward and add array[right] to the running sum.
As long as sum >= target, the window from left to right is a valid answer. Record its length if it is the shortest so far, then subtract array[left] and move left forward to try a shorter one.
When the sum drops below the target, go back to expanding. Every window that reaches the target gets squeezed down to its shortest form before right moves on.
Return the shortest length found, or 0 if the sum never reached the target.
The page loads [1, 2, 3, 2, 7, 8, 5] with target 15. Adding 1, 2, 3 and 2 gives 8, not enough. Adding 7 gives exactly 15 over indices 0 to 4, so the shortest so far is 5; dropping the 1 leaves 14 and expanding resumes. Adding 8 gives 22 over 1 to 5, length 5 again. Now the squeeze: drop 2 for 20 (length 4), drop 3 for 17 (length 3), drop 2 for 15 (length 2: just 7 and 8), and dropping the 7 leaves 8. Adding the final 5 gives 13, short of 15. The answer is 2.
The inner while loop looks expensive, but left only ever moves forward. Across the whole run it moves at most n times in total, so the two loops together do about 2n steps, not n².
Time: each value is added once when right reaches it and subtracted at most once when left passes it. Space: the running sum, two indices and the shortest length.