Problem Statement
Minimum Size Subarray Sum
You are given a list of positive numbers called nums and a target number. A subarray means a chunk of numbers that sit right next to each other in the list, with no gaps. Your job is to find the shortest such chunk whose numbers add up to at least the target, and return how many numbers are in it. If no chunk reaches the target, return 0. The trick we use is a sliding window. A sliding window is like a stretchy frame you lay over part of the list. It has a left edge and a right edge, and it only covers the numbers between them. You can stretch the right edge to cover more numbers (which makes the total bigger), and you can pull the left edge inward to drop numbers off the start (which makes the total smaller). This works here because every number is positive: adding a number always grows the total, and removing one always shrinks it. That dependable behavior is what lets us slide instead of checking every possible chunk.
Signals to notice
Brute force first
Check every subarray sum. Each subarray independently summed. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.
The key insight
Sliding window: expand right to accumulate sum ≥ target. Then shrink left to minimize length while maintaining sum ≥ target. Track the minimum length. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.
Trace it on target=7, nums=[2,3,1,2,4,3]
right=0: sum=2 (<7), window=[2]; best=INF right=1: sum=5 (<7); best=INF right=2: sum=6 (<7); best=INF right=3: sum=8>=7, best=min(INF,4)=4, shrink left0(2): sum=6, left=1 right=4: sum=10>=7, best=min(4,4)=4, shrink left1(3): sum=7>=7, best=min(4,3)=3, shrink left2(1): sum=6, left=3 right=5: sum=9>=7, best=min(3,3)=3, shrink left3(2): sum=7>=7, best=min(3,2)=2, shrink left4(4): sum=3, left=5 loop ends: best=2 != INF -> return 2
What must stay true
Because all numbers are positive, adding elements only increases the sum. Once the sum ≥ target, shrinking from the left finds the minimum window with that property. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.
Shape of the loop
left = 0; sum = 0; best = INF
for right in 0..n-1:
sum += nums[right]
while sum >= target: # window valid -> try to shrink
best = min(best, right - left + 1)
sum -= nums[left]; left += 1
return best if best != INF else 0Pseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
This only works with positive numbers — with negatives, shrinking from the left might increase the sum. For mixed numbers, you'd need a deque-based approach. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.