SDE & MLE Prep

209. Minimum Size Subarray Sum

Problem

Given positive integers nums, return the minimal length of a contiguous subarray whose sum is at least target, or 0 if none exists.

Example: target = 7, nums = [2,3,1,2,4,3] → 2 ([4,3])

Constraints: n ≤ 10⁵. Follow-up: also an O(n log n) solution.

All positive → expand r, and while sum ≥ target record the length and shrink from l.

Complexity: O(n) time, O(1) space.

class Solution:
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        l = s = 0
        best = float("inf")
        for r, x in enumerate(nums):
            s += x
            while s >= target:
                best = min(best, r - l + 1)
                s -= nums[l]
                l += 1
        return 0 if best == float("inf") else best