← Back to LeetCode Notes

209. Minimum Size Subarray Sum

medium · array · binary-search · sliding-window · prefix-sum · solved 2026.08.22 · 10 sec read

View on LeetCode ↗
C++
class Solution {public:    int minSubArrayLen(int target, vector<int>& nums) {        int l = 0;        int r = 0;        int best = INT_MAX;        int sum = 0;        // [l,r]        for (r = 0; r < nums.size(); r++) {            sum += nums[r];  // fix invarient so that we now have the new r                             // accomodated            while (sum >= target) {  // only fix sum is the inner sum is                                     // too big compared to                best = min(r - l + 1, best);                sum -= nums[l];                // the part i was getting confused here by was when l and                // sum were being changed, i thought the invarient I wanted                // was getting destroyed. but we had already logged the                // valid part right after the while loop did it's check                l++;            }        }        return best == INT_MAX ? 0 : best;    }};