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
Tested onlyIdea. 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;
}
Reflection
- Which cue made you pick this pattern in under 90 seconds?
- What input would break a wrong window invariant?