Given a positive integertargetand an array of positive integersnums, return the length of the shortest non-empty contiguous subarray whose sum is at leasttarget. Return0if no such subarray exists.
For target = 7 and nums = [2, 3, 1, 2, 4, 3], the shortest qualifying subarray is [4, 3], so the answer is 2.
Move right across the array and add each new value to window_sum. When the sum reaches target, the current window is valid, but values at its left edge may not be necessary. Record its length, then remove nums[left] and move left forward. Continue shrinking while the remaining sum is still at least target.
Because every value is positive, adding a value can only increase the window sum, while removing a value can only decrease it. Once removing nums[left] drops the sum below target, removing more values cannot make the window valid again. The algorithm must move right forward and add another value.
For a fixed right, moving left forward makes the window shorter. The loop records each window while its sum is still at least target, so the last valid length recorded is the shortest qualifying window ending at right. Comparing those candidates gives the shortest qualifying subarray overall.
Shrink every window whose sum reaches 7
- window_sum
- 2
- best_length
- not found
while loop instead of one if?If no window ever reaches the target, res remains infinity. The final return converts that sentinel to 0, as required by the problem.
Each value enters the window once and leaves it at most once, so the two pointers make O(n) total moves. The algorithm stores two boundaries, the current sum, and the best length.