← Back to Leo Academy Masterclass

Problem #209: Minimum Size Subarray Sum

Medium Sliding Window

Intuition & Strategy Breakdown

Use sliding window. Expand right pointer accumulating sum; while sum >= target, update min length and contract left pointer.

Python Solution

class Solution:
    def minSubArrayLen(self, target: int, nums: list[int]) -> int:
        l, total = 0, 0
        res = float("inf")
        for r in range(len(nums)):
            total += nums[r]
            while total >= target:
                res = min(r - l + 1, res)
                total -= nums[l]
                l += 1
        return 0 if res == float("inf") else res

Java Solution

class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int l = 0, total = 0, res = Integer.MAX_VALUE;
        for (int r = 0; r < nums.length; r++) {
            total += nums[r];
            while (total >= target) {
                res = Math.min(res, r - l + 1);
                total -= nums[l++];
            }
        }
        return res == Integer.MAX_VALUE ? 0 : res;
    }
}
Watch Interactive Video on Leo Academy Main App