209. Minimum Size Subarray Sum

two pointers - fix start, move end

class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int n = nums.length;
        int sum = 0;
        int res = Integer.MAX_VALUE;
        
        int end = 0;
        for (int start = 0; start < n; start++) {
            while (end < n && sum < target) {
                sum += nums[end];
                end++;
            } // when out while end is in next position
            if (sum >= target) {
                res = Math.min(res, end - start); // so it's end - start
            }
            sum -= nums[start];
        }
        return res == Integer.MAX_VALUE ? 0 : res;
    }
}


// ask minimal length of a contiguous subarray

// sum is greater than or equal to target(positive integer)

// no result: 0

two pointers - fix end, move start (my sliding win style)

T: O(n)

S: O(1)

Last updated

Was this helpful?