Minimum Size Subarray Sum

LeetCode 209 · View on LeetCode

Sliding window: expand right to grow the sum, shrink left once the sum meets the target. Track the minimum window length throughout.

def min_subarray_len(target: int, nums: list[int]) -> int:
    left = 0
    current = 0
    result = float('inf')
    for right, num in enumerate(nums):
        current += num
        while current >= target:
            result = min(result, right - left + 1)
            current -= nums[left]
            left += 1
    return result if result != float('inf') else 0

if __name__ == '__main__':
    print(min_subarray_len(7, [2, 3, 1, 2, 4, 3]))  # 2
    print(min_subarray_len(4, [1, 4, 4]))             # 1
    print(min_subarray_len(11, [1, 1, 1, 1, 1]))     # 0
© 2026 ByteLearn.dev. Free courses for developers. · Privacy