Minimum Size Subarray Sum
Problem (restated)
Given a positive integer array nums and a positive integer target, return the minimal length of a contiguous subarray whose sum is ≥ target. Return 0 if no such subarray exists.
Intuition
Because all values are positive, expanding the right end only increases the sum and shrinking the left only decreases it. classic variable window.
Approaches
Sliding window
UnverifiedIdea. Grow right while sum < target. When sum ≥ target, shrink left as far as possible and track min length.
Walkthrough. nums=[2,3,1,2,4,3], target=7. Window grows to [2,3,1,2] sum=8 → length 4. Shrink to [3,1,2] then [1,2,4]… eventually [4,3] length 2.
Trade-offs. Optimal linear scan. Binary search on prefix sums is O(n log n) and only needed if negatives appear (they do not here).
export function minSubArrayLen(target: number, nums: number[]): number {
let left = 0, sum = 0, best = Infinity;
for (let right = 0; right < nums.length; right++) {
sum += nums[right]!;
while (sum >= target) {
best = Math.min(best, right - left + 1);
sum -= nums[left++]!;
}
}
return best === Infinity ? 0 : best;
}
export function minSubArrayLen(target: number, nums: number[]): number {
let left = 0, sum = 0, best = Infinity;
for (let right = 0; right < nums.length; right++) {
sum += nums[right]!;
while (sum >= target) {
best = Math.min(best, right - left + 1);
sum -= nums[left++]!;
}
}
return best === Infinity ? 0 : best;
}
Template connection
Sliding window: grow right, shrink left while sum ≥ target, track min length.
Reflection
- Every value is positive, so extending the right end only raises the sum. What makes the window the right tool?
- Once
sum >= target, if you do not shrink the left as far as it will go, why does the answer stay too large? - A negative breaks this scan. What do you switch to? Prefix sums plus binary search.