AlgoInsight

DSA problem

Minimum Size Subarray Sum

MediumSliding Window - Dynamic SizePattern: Variable-Size Sliding Windowtop300AmazonGoogleMicrosoftFacebookGoldman Sachs

Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.

This problem flips the usual sliding-window goal: instead of finding the longest valid window, we want the shortest window that satisfies a constraint. The brute-force approach of testing every subarray sum is O(n^2), and we want to do better by exploiting a structural property of the input.

The crucial property is that all elements are positive. This means the prefix sum is strictly increasing, so extending a window can only increase its sum and shrinking it can only decrease its sum. That monotonic behavior is exactly what makes a two-pointer window valid here.

The intuition for the sliding window is a grow-then-shrink rhythm. Expand the right pointer to accumulate elements until the running sum reaches target. The moment the window is valid, record its length, then aggressively shrink it from the left while it remains valid, looking for an even shorter qualifying window. Because each pointer only moves forward, the entire scan runs in O(n) time.

Examples

Example 1
Input: target = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: The subarray [4,3] has a sum of 7, which meets the target, and its length of 2 is the smallest possible.
Example 2
Input: target = 4, nums = [1,4,4]
Output: 1
Explanation: The single element 4 already meets the target, so a subarray of length 1 is the minimum.
Example 3
Input: target = 11, nums = [1,1,1,1,1,1,1,1]
Output: 0
Explanation: The total sum of the array is only 8, which is less than 11, so no qualifying subarray exists and the answer is 0.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

sliding-windowarraytwo-pointersprefix-sum

Browse all DSA problems