Home
DSA Patterns
Sliding Window
Minimum Size Subarray Sum
Minimum Size Subarray Sum
Find the shortest subarray whose sum reaches a target in O(n) with a sliding window that grows on the right and shrinks from the left.
Problem Understanding
Minimum Size Subarray Sum: given an array of positive integers and a target, return the length of the shortest contiguous subarray whose sum is at least target, or 0 if there is none.
Example: target = 7, nums = [2, 3, 1, 2, 4, 3] returns 2: [4, 3].
The Intuition: Stretch, Then Squeeze
Because every number is positive, a window's sum goes up when it grows and down when it shrinks. That makes a variable-size sliding window work:
- Move
rightone step and addnums[right]tototal. - While
total ≥ target, the window is good enough: record its length, then removenums[left]and movelefton, looking for something shorter. - When the sum drops below the target, go back to growing.
Each number enters and leaves the window at most once, so the whole scan is O(n). Compare Longest Substring Without Repeating Characters, which shrinks for the opposite reason: to make an invalid window valid again.
Interactive Walkthrough
The shaded cells are the current window L..R; the number just added or dropped is filled. The best window so far is underlined in green. Watch the window stretch until the sum is enough, then pull in from the left.
Dry Run Table
Input: target = 7, [2, 3, 1, 2, 4, 3]
| Add | Window | Total | Shrink? | Best |
|---|---|---|---|---|
| 2, 3, 1 | 0..2 | 6 | no | — |
| 2 | 0..3 | 8 | record 4, drop 2 | 4 |
| 4 | 1..4 | 10 | record 4, drop 3; 7: record 3, drop 1 | 3 |
| 3 | 3..5 | 9 | record 3, drop 2; 7: record 2, drop 4 | 2 |
Return 2.
The Solution Template
Variable-size sliding window: grow right, shrink left while the sum is enough.
Minimum Size Subarray Sum Code
1var minSubArrayLen = function(target, nums) {2 let best = Infinity, total = 0, left = 0;3 for (let right = 0; right < nums.length; right++) {4 total += nums[right];5 while (total >= target) {6 best = Math.min(best, right - left + 1);7 total -= nums[left++];8 }9 }10 return best === Infinity ? 0 : best;11};
Edge Cases & Common Mistakes
- No window reaches the target: return 0, not infinity.
- A single number is enough: the answer is 1.
- Using
ifinstead ofwhileto shrink: the window may need to drop several numbers before it stops being enough. - Recording the length after shrinking: record it while the sum still reaches the target, before removing
nums[left].
Summary
With only positive numbers, a window's sum grows and shrinks predictably. Extend the window on the right; while its sum reaches the target, record its length and drop numbers from the left. Each number enters and leaves once: O(n) time, O(1) space.
More practice: DSA interview questions with answers · patterns cheat sheet
