Find the minimum length of a contiguous subarray whose sum is at least a given target.
Use a variable sliding window: expand the right boundary to grow the sum, and once the sum meets the target, shrink from the left as much as possible while still staying at or above the target. Record the window length each time it qualifies. One O(n) pass.
How to think about it
Recognise the pattern
The signal is “minimum length / shortest window” + contiguous subarray + positive integers + sum condition. The positive-integers constraint is crucial: it means adding elements always grows the sum, and removing them always shrinks it. That monotonicity is what lets a sliding window work — if you had negative numbers, removing an element from the left might accidentally increase the sum, breaking the shrink step.
Build the approach step by step
Brute force tries every (i, j) pair, computes the subarray sum, checks against target. O(n²).
The sliding window approach:
- Use
left=0,right=0, runningwindow_sum=0, andbest=infinity. - Expand: add
nums[right]towindow_sum, advanceright. - Shrink: while
window_sum >= target, recordright - leftas a candidate answer, then subtractnums[left]and advanceleft. - Repeat until
rightreaches the end.
Why does this work? Every time the window is valid (sum >= target), we greedily shrink from the left to find the shortest valid window ending at the current right. Because all values are positive, shrinking can only decrease the sum, so we stop shrinking the moment the constraint breaks.
Walk through [2, 3, 1, 2, 4, 3], target=7:
- right grows until sum=7 (window [2,3,1,2,4] len=5? no, let’s trace):
sum = 2,3,4,6,10at right=4:10 >= 7, record len=5, shrink left:sum = 8, record len=4,sum = 5 < 7stop- right=5:
sum = 8, record len=3, shrink:sum = 7, record len=2, shrink:sum = 3 < 7stop
- Best = 2 ✓
Complexity
- Time — O(n):
rightadvances n times;leftadvances at most n times total across all iterations of the innerwhile. Each element enters and exits the window exactly once. - Space — O(1): a handful of variables.