Visualize LeetCode 209 step by step. Watch the variable sliding window expand to accumulate sum and shrink to find the minimum length subarray ≥ target.
Use two pointers (left, right). Expand right to grow the window and accumulate sum. Once sum ≥ target, try shrinking from the left to minimize window length.
While sum ≥ target: record current window length as a candidate for the minimum, then remove the leftmost element and advance left. This ensures we find the shortest window.
Each element is added at most once (right pointer) and removed at most once (left pointer). So the total operations across all iterations is O(2N) = O(N).
There is also an O(N log N) approach: build prefix sums, then for each index i binary search for the smallest j ≥ i such that prefix[j] − prefix[i] ≥ target. The O(N) sliding window is strictly better.
Works only for arrays with positive integers. For negative numbers, use prefix sums + monotonic deque (LeetCode 862).