Minimum Size Subarray Sum
Find the shortest subarray whose sum is at least target.
Find the minimum length of a contiguous subarray whose sum is at least target. Because all numbers are positive, once the window reaches target you should shrink immediately.
Pattern fit
All numbers are positive, so once the current sum reaches the target, shrinking the left side is the only way to search for a shorter valid window.
Key observation
Positivity makes the window sum monotonic with pointer movement, which is exactly why sliding window beats prefix-sum search here.
Target complexity
O(n) / O(1)
How to break down the solution cleanly
Maintain a running sum for the current window.
Expand right until the sum reaches or exceeds target.
While the window is still valid, update the answer and shrink from the left.
The positivity guarantee is what makes this shrinking logic correct.
Walk through one example
Example: target = 7, nums = [2, 3, 1, 2, 4, 3].
After expanding to [2, 3, 1, 2], sum = 8, so answer can be 4.
Shrink left to get [3, 1, 2], sum = 6, which becomes invalid.
Continue until [4, 3] appears, and answer improves to 2.
Reference implementation
Pythondef minSubArrayLen(target: int, nums: list[int]) -> int:
left = 0
window_sum = 0
best = float("inf")
for right, value in enumerate(nums):
window_sum += value
while window_sum >= target:
best = min(best, right - left + 1)
window_sum -= nums[left]
left += 1
return 0 if best == float("inf") else best
Common pitfalls
Using sliding window on arrays that may contain negatives.
Updating the answer before shrinking all still-valid prefixes.
Common follow-ups
Why would negatives break the same window logic?
How would a prefix-sum + binary-search solution compare?
Continue with related problems
Build repeatable depth inside the Sliding Window cluster before moving on.