Use a shrinking sliding window to find the shortest qualifying subarray.
Use the editor below to find the shortest contiguous window whose sum reaches the target.
Shrink the window when it reaches the target
The positive input values allow the window to shrink safely whenever its sum is large enough. Return 0 if no window reaches the target.
Submit your implementation when it passes the examples.
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.
1 ≤ nums.length ≤ 100,000Results appear here after a run.
Start with shortest = 0 to show that no window has reached the target yet. Expand the right edge and add each value to the running sum. While the sum is at least the target, save the current length if it is the first qualifying length or shorter than the best so far. Then remove the leftmost value and check the smaller window.
For target 7, suppose the current window is [1, 2, 4, 3] with sum 10. Removing 1 leaves sum 9. Removing 2 leaves [4, 3] with sum 7. Record length two before removing 4 makes the sum too small.
function minSubArrayLen(target, nums) {
let left = 0;
let sum = 0;
let shortest = 0;
for (let right = 0; right < nums.length; right++) {
sum += nums[right];
while (sum >= target) {
const length = right - left + 1;
if (shortest === 0 || length < shortest) {
shortest = length;
}
sum -= nums[left];
left++;
}
}
return shortest;
}| 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. |