209. Minimum Size Subarray Sum
At a Glance
- Topic: sliding-window
- Pattern: Sliding Window
- Difficulty: Medium
- Companies: Google, Amazon, Meta, Goldman Sachs, Microsoft
- Frequency: High
- LeetCode: 209
Problem (one-liner)
Given an array of positive integers nums and a target target, return the minimal length of a contiguous subarray whose sum is at least target. Return 0 if none exists.
Recognition Cues
- Positive integers → window sum monotonic as you extend
- "Shortest subarray with sum ≥ target"
- Classic variable-size window with shrink-from-left
Diagram
At-a-glance flow (replace with problem-specific Mermaid as you refine this note). camelCase node IDs; no spaces in IDs.
Loading diagram…
Approaches
- Brute force — all subarrays —
O(n³)naïve,O(n²)with prefix sums. - Better — sliding window —
O(n)time /O(1)space for positives. - Optimal — same sliding window; not valid if negatives allowed (then prefix sum + deque/monotonic).
Optimal Solution
Go
func minSubArrayLen(target int, nums []int) int {
left := 0
sum := 0
best := len(nums) + 1
for right := 0; right < len(nums); right++ {
sum += nums[right]
for sum >= target {
width := right - left + 1
if width < best {
best = width
}
sum -= nums[left]
left++
}
}
if best == len(nums)+1 {
return 0
}
return best
}JavaScript
function minSubArrayLen(target, nums) {
let left = 0;
let sum = 0;
let best = nums.length + 1;
for (let right = 0; right < nums.length; right++) {
sum += nums[right];
while (sum >= target) {
const width = right - left + 1;
if (width < best) {
best = width;
}
sum -= nums[left];
left++;
}
}
return best === nums.length + 1 ? 0 : best;
}Walkthrough
Input: target = 7, nums = [2,3,1,2,4,3]
| right | sum | shrink while ≥7 | best |
|---|---|---|---|
| … | 7 | window [2,3,1,1] too long — shrink left until sum<7 | record min width |
Invariant: for each right, minimal valid window ending at right is found by maximizing left while sum still ≥ target.
Edge Cases
- Total sum < target →
0 - Single element equals target
- Entire array needed
Pitfalls
- Including zeros or negatives breaks monotonicity — solution template changes
- Initializing
bestto zero incorrectly (use sentinel max)
Similar Problems
- 904. Fruit Into Baskets — longest window with constraint (dual pointer style).
- 3. Longest Substring Without Repeating — another expand/shrink narrative.
- 121. Best Time to Buy and Sell Stock — one-pass min tracking (canonical file in arrays-hashing).
Variants
- Sum exactly equals target with non-negative — prefix sum + hashmap count.
- With negatives — shortest subarray with deque on prefix minima.
Mind-Map Tags
#sliding-window #variable-window #prefix-sum-window #positive-integers #minimum-length
Last updated on
Spotted something unclear or wrong on this page?