Minimum Size Subarray Sum
Use a shrinking sliding window to find the shortest qualifying subarray.
Try It Yourself
Use the editor below to find the shortest contiguous window whose sum reaches the target. The positive input values allow the window to shrink safely whenever its sum is large enough.
Submit your implementation when it passes the examples. Return zero if no window reaches the target.
Minimum Size Subarray Sum
Given an array of positive integers nums and a positive integer target, return the smallest length of a contiguous subarray whose sum is at least target.
Return 0 when no qualifying subarray exists.
Example 1:
Example 2:
Constraints
1 ≤ nums.length ≤ 100,000- All values and target are positive integers.
Solution
Expand the right edge and add each value to the running sum. Whenever the sum reaches the target, record the current length and repeatedly remove values from the left to search for a shorter valid window.
If no valid length was recorded, return zero.
function minSubArrayLen(target, nums) {
let left = 0;
let sum = 0;
let shortest = Infinity;
for (let right = 0; right < nums.length; right++) {
sum += nums[right];
while (sum >= target) {
shortest = Math.min(shortest, right - left + 1);
sum -= nums[left];
left++;
}
}
return shortest === Infinity ? 0 : shortest;
}Big O notation
| Measure | Complexity | Explanation |
|---|---|---|
| Time | O(n) | Each value is added once and removed from the window at most once. |
| Auxiliary space | O(1) | The window is represented by indices and a running sum. |