Given an array of positive integers nums and a positive integer target, return the minimum length of a subarray whose sum is greater than or equal to target. Return 0 if no such subarray exists.
target = 7, nums = [2,3,1,2,4,3]2Since all elements are positive, adding an element always increases the sum and removing one always decreases it. This monotonic property lets us use two pointers: expand right to grow the sum until it meets the target, then shrink left to find the tightest valid window. Each element is added and removed at most once, giving O(n) overall.
Trying every start and end is O(n²). Because every number is positive, growing a window only increases its sum, and shrinking only decreases it.
Expand the window to the right until its sum reaches the target. Then shrink it from the left as far as possible, while it still reaches the target. Every time the window is valid, record its length.
With positive numbers, expand until valid, then shrink while still valid. Record the answer inside the shrinking loop.
Run the animation above on your own input, or watch the 1:39 video explanation of Minimum Size Subarray Sum with a dry run and Java code.