Minimum Size Subarray Sum
Given positive integers nums and a target, return the length of the shortest contiguous subarray whose sum is at least target , or 0 if none exists. Grow the sum on the right, then shrink from the left while the sum still meets the target to minimize length.
Constraints
- 1 ≤ target ≤ 109
- 1 ≤ nums.length ≤ 105
- 1 ≤ numsi ≤ 104
Example
Input
target = 7, nums = [2, 3, 1, 2, 4, 3]Output
2Explanation The subarray [4, 3] has sum 7 and is the shortest that qualifies.
Shrink while sum stays >= target
02
13
21
32
44
53
Statushit
Window [2,3,1,2] sums to 8 >= 7; length 4 is a candidate.
What happens in this step
window = [0, 3] sum = 2+3+1+2 = 8 before: sum = 6 (right = 2), best = Infinity add nums[3] = 2 → sum = 8 8 >= target 7, so this whole window is a valid candidate — best becomes 4 (its length).
Step 1 of 4
Steps to visualize
- Grow right and add each new value into the running window sum.
- While the sum is at least target, record the window length as a candidate.
- Then drop the leftmost value and advance left to try a shorter window.
- Keep the smallest length that still meets the target.
- If no window ever qualifies, return 0.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
02
13
21
32
44
53
Statushit
Window [2,3,1,2] sums to 8 >= 7; length 4 is a candidate.
What happens in this step
window = [0, 3] sum = 2+3+1+2 = 8 before: sum = 6 (right = 2), best = Infinity add nums[3] = 2 → sum = 8 8 >= target 7, so this whole window is a valid candidate — best becomes 4 (its length).
Step 1 of 4
Solution
function minSubArrayLen(target, nums) {
let left = 0;
let sum = 0;
let 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];
left++;
}
}
return best === Infinity ? 0 : best;
}- Time
- O(n)
- Space
- O(1)
Test cases
| Input | Expected | Covers |
|---|---|---|
target = 7, nums = [2, 3, 1, 2, 4, 3] | 2 | Docstring example — [4, 3] |
target = 5, nums = [5] | 1 | Single element meeting target |
target = 15, nums = [1, 2, 3, 4, 5] | 5 | Entire array is the answer |
target = 100, nums = [1, 2, 3] | 0 | No valid window exists |
target = 9, nums = [3, 3, 3, 3, 3] | 3 | All identical elements |
target = 4, nums = [1, 4, 4] | 1 | Classic LeetCode example with a single 4 |
target = 11, nums = [1, 2, 3, 4, 5] | 3 | Best is [3, 4, 5] length 3 |