DSA AnimatorDSA animations
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.

How to solve Minimum Size Subarray Sum

LeetCode 209 · Medium · Arrays · Pattern: Sliding Window

Why the obvious approach is slow

Trying every start and end is O(n²). Because every number is positive, growing a window only increases its sum, and shrinking only decreases it.

The key idea

Expand the window to the right until its sum reaches the target. Then shrink it from the left as far as possible, while it still reaches the target. Every time the window is valid, record its length.

Remember

With positive numbers, expand until valid, then shrink while still valid. Record the answer inside the shrinking loop.

Run the animation above on your own input, or watch the 1:39 video explanation of Minimum Size Subarray Sum with a dry run and Java code.

More Arrays problems