Minimum Size Subarray Sum
Difficulty: Medium · Pattern: Sliding Window · LeetCode #209
Given positive integers nums and a positive target, return the minimum length of a contiguous subarray whose sum is at least target, or 0 if none exists.
Examples
text
target = 7, nums = [2, 3, 1, 2, 4, 3] → 2 ([4, 3])
target = 4, nums = [1, 4, 4] → 1
target = 11, nums = [1, 1, 1, 1, 1] → 0Hints
- All numbers are positive, so extending a window only increases its sum.
- Grow the right edge until the sum is ≥ target, then shrink from the left as much as possible.
Approach
Variable-size window: add nums[r] to the sum; while sum ≥ target, record r − l + 1 and subtract nums[l++]. Positivity guarantees monotonicity: shrinking always decreases the sum, so we never miss a shorter valid window. Each index enters and leaves once, so O(n).
Complexity
Time: O(n). Space: O(1).
Python solution
def minSubArrayLen(target, nums):
l = s = 0
best = float('inf')
for r, x in enumerate(nums):
s += x
while s >= target:
best = min(best, r - l + 1)
s -= nums[l]; l += 1
return 0 if best == float('inf') else bestJavaScript solution
function minSubArrayLen(target, nums) {
let l = 0, s = 0, best = Infinity;
for (let r = 0; r < nums.length; r++) {
s += nums[r];
while (s >= target) { best = Math.min(best, r - l + 1); s -= nums[l++]; }
}
return best === Infinity ? 0 : best;
}