← Back to DSA Animator
Minimum Size Subarray Sum LC #209 Medium Sliding Window
Problem

Given an array of positive integers nums and a positive integer target, return the minimum length of a subarray whose sum is greater than or equal to target. Return 0 if no such subarray exists.

Example 1
Input: target = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: Subarray [4,3] has the minimal length with sum ≥ 7.
Constraints: 1 ≤ target ≤ 10⁹  |  1 ≤ nums.length ≤ 10⁵  |  1 ≤ nums[i] ≤ 10⁴
Try Examples
Custom:
Approach
Sliding Window (Variable Size)
Expand right pointer to grow the window sum. Once sum ≥ target, record the window length and shrink from the left to find the minimum. Each element enters and leaves the window at most once — O(n).
Sliding Window
Variables
L pointer
R pointer
sum
minLen
Step Logic
Press ▶ Play or Next Step to begin.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
L=0, sum=0, minLen=∞
2
Expand R: sum += nums[R]
3
While sum ≥ target: update minLen = min(minLen, R−L+1), shrink: sum −= nums[L], L++
4
Return minLen (or 0 if still ∞)
Time
O(n)
Space
O(1)
Why It Works

Since all elements are positive, adding an element always increases the sum and removing one always decreases it. This monotonic property lets us use two pointers: expand right to grow the sum until it meets the target, then shrink left to find the tightest valid window. Each element is added and removed at most once, giving O(n) overall.