</>

209. Minimum Size Subarray Sum

Medium
Sliding Window Time O(N) Space O(1)
↗ Open on LeetCode Source: Misc

Quick review

Pattern
Sliding Window
Time
O(N)
Space
O(1)

Standard Solution (C++)

SummaryGiven a positive integer target and an array of positive integers, find the minimum length of a contiguous subarray whose sum is at least target, returning 0 if no such subarray exists.

Approach
  • Use a sliding window with two pointers (left and right) that expand by advancing right and shrink by advancing left.
  • Whenever the current window sum meets or exceeds target, record the window length and then shrink from the left to find a potentially smaller valid window.
  • Because all values are positive, shrinking always decreases the sum, so each pointer moves forward at most n times — giving linear time overall.
#include <vector>
#include <climits>
using namespace std;

class Solution {
public:
    int minSubArrayLen(int target, vector<int>& nums) {
        int left = 0, windowSum = 0;
        int minLen = INT_MAX;

        for (int right = 0; right < (int)nums.size(); ++right) {
            windowSum += nums[right];

            // Shrink from the left as long as the window satisfies the condition.
            while (windowSum >= target) {
                minLen = min(minLen, right - left + 1);
                windowSum -= nums[left++];
            }
        }

        return minLen == INT_MAX ? 0 : minLen;
    }
};
Time O(n) Space O(1)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

#include <vector>
#include <climits>
using namespace std;

class Solution {
public:
    int minSubArrayLen(int target, vector<int>& nums) {
        int minLen=INT_MAX;
        int left=0;
        int curSum=0;

        for(int right=0; right<nums.size(); ++right){
            // expand window
            curSum+=nums[right];
            if(curSum>=target){
                // reduce window
                while(curSum>=target){
                    curSum-=nums[left];
                    ++left;
                }
                minLen=std::min((right-left+2), minLen);
            }
        }
        if(minLen==INT_MAX){
            return 0;
        }

        return minLen;
    }
};

// Time Complexity: O(N)
// Space Complexity: O(1)
Time O(N) Space O(1)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern