Minimum Size Subarray Sum (LeetCode 209): Solution and Explanation
Given an array of positive integers and a positive target, find the length of the shortest contiguous subarray whose sum is at least target. If no subarray reaches the target, return 0.
Watch it run step by step
Try your own input and write the code →Intuition
Brute force tries every starting index and extends to the right until the running sum reaches the target, keeping the shortest length found. That is O(n²) and repeats a lot of addition, since neighboring start points share almost all of their sums.
The fact that every number is positive is the key. It means extending a window always increases its sum and shrinking it always decreases the sum. So once a window from left to right reaches the target, there is no reason to extend it further for that left; any longer window starting there is worse. And if a window ending at right falls short, every window ending at right with a later start is even smaller.
That monotonic behavior gives a two-pointer sliding window. Move right forward, adding each value. Whenever the sum reaches the target, record the window length, then drop nums[left] and advance left, repeating while the sum stays large enough. Each pointer only moves forward, so the total work is linear. Note that this logic breaks if negative numbers are allowed, which is why the constraints matter.
Approach: Variable-size sliding window
- Initialize
left = 0,curr_sum = 0andmin_lento infinity. - For each index
right, addnums[right]tocurr_sum. - While
curr_sum >= target, updatemin_lenwithright - left + 1. - Inside that loop, subtract
nums[left]fromcurr_sumand incrementleftto try a shorter window. - After processing every index, return 0 if
min_lenis still infinity, otherwise returnmin_len.
Step-by-step example
target = 7, nums = [2,3,1,2,4,3]
- Adding 2, 3 and 1 brings the sum to 6, still below 7.
- Adding 2 at index 3 makes the sum 8. Record length 4, then drop the leading 2, leaving a sum of 6 with
leftat 1. - Adding 4 at index 4 makes the sum 10. Record length 4, then drop 3 to get 7, which still qualifies, so record length 3 for [1,2,4]. Dropping 1 leaves 6.
- Adding 3 at index 5 makes the sum 9. Record length 3, then drop 2 to get 7 and record length 2 for [4,3]. Dropping 4 leaves 3.
- The array is finished, so the answer is 2.
Code: Python, Java, C++
1class Solution:
2 def minSubArrayLen(self, target: int, nums: List[int]) -> int:
3 left = 0
4 curr_sum = 0
5 min_len = float('inf')
6 for right in range(len(nums)):
7 curr_sum += nums[right]
8 while curr_sum >= target:
9 min_len = min(min_len, right - left + 1)
10 curr_sum -= nums[left]
11 left += 1
12 return 0 if min_len == float('inf') else min_len1class Solution {
2 public int minSubArrayLen(int target, int[] nums) {
3 int left = 0, sum = 0;
4 int minLen = Integer.MAX_VALUE;
5 for (int right = 0; right < nums.length; right++) {
6 sum += nums[right];
7 while (sum >= target) {
8 minLen = Math.min(minLen, right - left + 1);
9 sum -= nums[left];
10 left++;
11 }
12 }
13 return minLen == Integer.MAX_VALUE ? 0 : minLen;
14 }
15}1class Solution {
2public:
3 int minSubArrayLen(int target, vector<int>& nums) {
4 int left = 0, sum = 0;
5 int minLen = INT_MAX;
6 for (int right = 0; right < nums.size(); right++) {
7 sum += nums[right];
8 while (sum >= target) {
9 minLen = min(minLen, right - left + 1);
10 sum -= nums[left];
11 left++;
12 }
13 }
14 return minLen == INT_MAX ? 0 : minLen;
15 }
16};Time and space complexity
O(n)
The right pointer visits each index once and left never moves backward, so each element is added once and subtracted at most once.
O(1)
Only a few integer variables are kept regardless of the array size.
Other approaches
Prefix sums with binary search (time O(n log n), space O(n))
Build a prefix sum array, which is strictly increasing because all values are positive. For each start index, binary search for the first prefix that is at least the start prefix plus target. This is the O(n log n) follow-up the problem mentions.
Brute force over start indices (time O(n²), space O(1))
For each start, extend to the right while accumulating a sum and stop as soon as it reaches the target, keeping the minimum length. Simple, but quadratic on large inputs.
Common mistakes
- Using
ifinstead ofwhilefor the shrinking step. One window may qualify for several shorter lengths in a row. - Recording the length after subtracting
nums[left]and movingleft, which measures a window one element too short. - Returning infinity or a huge sentinel when no subarray qualifies instead of 0.
- Applying the same sliding window to arrays with negative numbers, where shrinking can increase the sum and the logic no longer holds.
Frequently asked questions
Why does the sliding window work for Minimum Size Subarray Sum?
All numbers are positive, so adding elements always raises the sum and removing them always lowers it. That lets you shrink from the left whenever the target is met without ever missing a shorter valid window.
What is the O(n log n) solution?
Compute prefix sums, which increase strictly for positive input. For each start, binary search the prefix array for the earliest end where the sum reaches the target.
What if the array contains negative numbers?
The sliding window no longer works because shrinking can increase the sum. You would use prefix sums with a monotonic deque instead, as in the shortest subarray with sum at least K problem.
Why does the inner loop use while instead of if?
After a large element enters on the right, the window may stay above the target even after dropping several elements from the left. A while keeps shrinking and recording shorter lengths until the sum dips below the target, which is how [4,3] is found in the example.